ISO8601 Date in PHP with Format YYYY-MM-DDTHH:MM:SS.mmmmmmmZ

25.1k views Asked by At

I am trying to generate a timestamp in PHP for use with an API. I cannot seem to get the timestamp to format as it should. The proper format is:

UTC ISO8601 DateTime format: YYYY-MM-DDTHH:MM:SS.mmmmmmmZ

Example: 2013-04-24T11:11:50.2829708Z

Edit, Let me clarify on the actual issue I am having:

The 'Z' Property is returning the timezone offset in seconds. I need the offset returned as date('c') returns it.

Example: +01:00 instead of 3600

Is there a built in function for this in PHP?

2

There are 2 answers

4
sjagr On BEST ANSWER

You are looking for the DateTime::format method in combination with the c formatter or the DateTime::ISO8601 constant:

$timestamp = new DateTime();
echo $timestamp->format('c'); // Returns ISO8601 in proper format
echo $timestamp->format(DateTime::ISO8601); // Works the same since const ISO8601 = "Y-m-d\TH:i:sO"
0
nkh On

To print date in ISO 8601 in PHP you can use the rather simple procedural style date() function like that:

$isoDate = date('c') // outputs 2017-10-18T22:44:26+00:00 'Y-m-d\TH:i:sO'  

Or if you prefer to OOP style then you can use DateTime() like this:

$date = DateTime('2010-01-01');
echo date_format($date, 'c');

The list of date format/constants that PHP provides are mentioned here:

const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-Y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;

So good thing is that we have ISO 8601 format in there. However, the value may not be same as you're expecting (YYYY-MM-DDTHH:MM:SS.mmmmmmmZ). According to ISO 8601 Wikipedia page, these are the valid formats:

2017-10-18T22:33:58+00:00
2017-10-18T22:33:58Z
20171018T223358Z

PHP probably prefers the first one. I was having somewhat similar problem dealing with dates between PHP and Javascript, because Javascript one has a trailing Z at the end. I ended up writing this to fix the issue:

$isoDate = date('Y-m-d\TH:i:s.000') . 'Z'; // outputs: 2017-10-18T23:04:17.000Z

NOTE: the reason I have 3 decimals is I noticed that Javascript date is using this format, it may not be necessary for you.