Search code examples
phpdatetimetimezoneiso8601

Convert DateTime to ISO 8601 DateTime Format with timezone


How do I convert my time from 2010-12-30 23:21:46 to ISO 8601 date format?

I tried $datetime->format(DateTime::ATOM) and date(DATE_ISO8601, strtotime('2010-12-30 23:21:46')) which converts into ISO8601 format like 2016-12-31T09:47:50+0000. But what i need is 2018-02-19T05:43:59.753000Z format. How can i achieve using PHP??


Solution

  • If you wish to output format in Zulu/UTC/GMT timezone, then you must first convert timezone, since I do not know in which timezone is your current setup.

    $dt = new DateTime('2010-12-30 23:21:46');
    $dt->setTimezone(new DateTimeZone('UTC'));
    echo $dt->format('Y-m-d\TH:i:s.u\Z');
    

    demo


    And ISO-8601 is a standard that has many variations of format:

    • 2018-04-03
    • 2018-04-03T05:20:03+00:00
    • 2018-04-03T05:20:03Z
    • 20180403T052003Z
    • 2018-W14
    • 2018-W14-2
    • ...

    This are all valid ISO-8601 formats. Read more here.