Search code examples
phpmysqljsontimestampmilliseconds

converting Mysql date to milliseconds in JSON using php


I have RESTfully encoded JSON from MySQL using PHP, one column is date, which in MySQL comes like this 01/03/15 06:00, on JSON encoding it comes like this.

[["01/03/15 06:00","89"],["02/03/15 06:00","87"]]

How do i convert this to below code, where date in milliseconds timestamp

[["1420245000000","89"],["1422923400000","87"]]

PHP code for JSON Encode

private function productionhourlys(){   
        if($this->get_request_method() != "GET"){
            $this->response('',406);
        }
        $query="SELECT distinct  c.Date, c.RoA FROM productionhourlys c order by c.productionhourlyNumber desc";
        $r = $this->mysqli->query($query) or die($this->mysqli->error.__LINE__);

        if($r->num_rows > 0){
            $result[] = array_values([]);
            while($row = $r->fetch_row()) {
                $result[] = $row;
            }
            $this->response($this->json($result), 200); // send user details
        }
        $this->response('',204);    // If no records "No Content" status
    }

Solution

  • If you want to do the conversion on the server side then do it inside your while loop before you assign the current $row to $result:

    EDIT: converted timestamp in seconds to milliseconds as OP asked

    while($row = $r->fetch_row()) {
        $row[0] = strtotime($row[0]); // convert to unix timestamp (in seconds)
        $row[0] = 1000 * $row[0]; // convert seconds to milliseconds
        $result[] = $row;
    }
    

    I'm also not certain what the purpose of this line is:

    $result[] = array_values([]);
    

    If you're simply creating a new empty array you can do:

    $result = array();