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

前端 未结 5 1347
闹比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:12

    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');
    }
    
    0 讨论(0)
  • 2020-12-02 17:21

    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.

    0 讨论(0)
  • 2020-12-02 17:30

    If you are using Carbon then the method is:

    echo $dt->toIso8601ZuluString();    
    // 2019-02-01T03:45:27Z
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 17:38

    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'));
    
    0 讨论(0)
提交回复
热议问题