I need to display and handle UTC dates in the following format:
2013-06-28T22:15:00Z
As this format is part of the ISO8601 stand
To do this with the object-oriented style date object you need to first set the timezone to UTC, and then output the date:
function dateTo8601Zulu(\DateTimeInterface $date):string {
return $date
->setTimezone(new \DateTimeZone('UTC'))
->format('Y-m-d\TH:i:s\Z');
}
No, there is no special constant for the desired format. I would use:
$date->format('Y-m-d\TH:i:s\Z');
But you will have to make sure that the times you are using are really UTC to avoid interpretation errors in your application.
If you are using Carbon then the method is:
echo $dt->toIso8601ZuluString();
// 2019-02-01T03:45:27Z
The Zulu time zone (Z) is exactly the same as Coordinated Universal Time (UTC). Interestingly, PHP recognizes "Z" as a valid timezone code although it's not listed among supported timezones.
That allows to leverage the built-in format character "T" that renders the timezone abbreviation dynamically instead of the hard-coded "Z" suffix.
$zulu = $date->setTimeZone(new \DateTimeZone('Z'));
echo $zulu->format('Y-m-d\TH:i:sT');
// 2020-05-20T21:09:48Z
The example assumes \DateTimeImmutable
instance that gets cloned by the timezone setter while keeping the original instance intact.
UPDATE: Initially, the answer featured the built-in constant \DateTime::RFC3339
that relies on the format character "P" instead of the needed "T" making it not suitable. Admittedly, the solution has lost its appeal as it now requires to explicitly specify the format just like the alternatives.
In order to get the UTC date in the desired format, you can use something like this:
gmdate('Y-m-d\TH:i:s\Z', $date->format('U'));