'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 1:[1]

You should be setting the date_default_timezone_set to UTC for your desired output. Format as you wish. And make sure to escape special characters in the format.

date_default_timezone_set('UTC');
$epoch = 1340000000;
echo gmdate('r', $epoch);

Solution 2:[2]

You can convert to UTC format date from a date string, for example:

$date = '2022-05-02 11:50:00';
$date = date('Y-m-d\TH:i:s\Z', strtotime($date));

echo $date;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harish Prasanna
Solution 2 Aldan