How to format an UTC date to use the Z (Zulu) zone designator in php?

前端 未结 5 1372
闹比i
闹比i 2020-12-02 17:11

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

5条回答
  •  青春惊慌失措
    2020-12-02 17:33

    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.

提交回复
热议问题