-3

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.

infernal_lad
  • 425
  • 1
  • 7
  • 13
  • Well you won’t get any milliseconds because those aren’t in the resolution of the Unix timestamp value in seconds – so you might want to fill those with zeros instead. And if you want a literal T and Z instead of them being replaced by the actual time zone name and offset, then escape them … – CBroe Jun 25 '14 at 21:04
  • thanks CBroe. That helped. I got my expected format by using the below code. $start = new DateTime(date('r', '1372190184')); $startDateText = $start->format('Y-m-d\TH:i:s.000\Z'); var_dump($startDateText); exit(); – infernal_lad Jun 25 '14 at 21:21

3 Answers3

3

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.

Aeveus
  • 5,052
  • 3
  • 30
  • 42
0

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);
Harish Prasanna
  • 108
  • 1
  • 8
0

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;
Aldan
  • 674
  • 9
  • 23