PHP date() returning format yyyy-mm-ddThh:mm:ss.uZ

Patrick picture Patrick · Jul 7, 2014 · Viewed 26.4k times · Source

I have checked out the following question/responses: How do I get the format of “yyyy-MM-ddTHH:mm:ss.fffZ” in php? The responses include links to Microsoft documentation to format dates but these do not work in PHP.

The the top answer suggest

date('Y-m-dTH:i:s.uZ') //for the current time

This outputs 2013-03-22EDT12:56:35.000000-1440016

Background

I am working with an API which requires a timestamp in the format above. The API is based in the UK (GMT) and my server is in Australia (AEST).

The example given in the API documentation ask for the date to be in this format:

2011-07-15T16:10:45.555Z

The closest I can get to this is date('c') which outputs:

2014-07-03T16:41:59+10:00//Notice the Z is replaced with a time diff in hours

I believe the 'Z' refers to a Zone but it is not mentioned in the PHP documentation.

Unfortunatly when I post this format, the API is reading the time and taking 10 hours off. I get an error saying that the date cannot be in the past (as it is checking against the local time in Melbourne, but seeing a time 10 hours earlier).

I have tried trimming the timestamp to remove the +1000 which the API accepts, but the record is showing as created as 10 hours earlier.

I need to match the timestamp required but I cannot find any way to replicate the above output, in PHP for Melbourne, Australia. Any assistance is much appreciated.

First question on SO so please let me know how I have gone

Answer

hek2mgl picture hek2mgl · Jul 7, 2014

Z stands for the timezone UTC and is defined in ISO-8601, which is your desired output format, extended by the millisecond part.

Before outputting the time, you'll need to transfer local times to UTC:

$dt = new DateTime();
$dt->setTimeZone(new DateTimeZone('UTC'));

then you can use the following format string:

echo $d->format('Y-m-d\TH-i-s.\0\0\0\Z');

Note that I've zeroed the millisecond part and escaped the special characters T and Z in the format pattern.