Search code examples
phpdatetimedate-formatutcepoch

How can I convert a epoch time stamp to a UTC format like 2014-06-25T14:38:52.359Z in PHP


I am looking to convert an EPOCH timestamp (like 1372190184) to a format 2014-06-25T14:38:52.359Z.

I have tried the following code, but the format I get is different from what I need.

$start = new DateTime(date('r', '1372190184'));
$startDateText = $start->format('Y-m-dTH:i:sZ');
var_dump($startDateText);
exit();

But I get the output as string(30) "2013-06-25GMT+020021:56:247200" which is different from what I expect.


Solution

  • You forgot the backslashes in your format, and the dollar sign before startDateText in the dump:

    $start = new DateTime(date('r', '1372190184'));
    $startDateText = $start->format('Y-m-d\TH:i:s\Z');
    var_dump($startDateText);
    

    Also, if you're looking for microseconds, add the u format character.