phpdatetimejava-dateformatdatetime-formattime-format

How do I convert datetime to ISO 8601 in PHP?


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


Solution

  • Object Oriented

    $datetime = new DateTime('2010-12-30 23:21:46');
    echo $datetime->format(DateTime::ATOM);
    

    Procedural

    If you are more comfortable with procedural code using at least php@7.0.33:

    echo date(DATE_ATOM, strtotime('2010-12-30 23:21:46'));
    

    Be aware that DATE_ISO8601 does not generate valid ISO8601 string, as it does not add the : in the time zone offset.

    DATE_ISO8601 (string) ISO-8601 (example: 2005-08-15T15:52:01+0000)

    Note: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use DATE_ISO8601_EXPANDED, DATE_ATOM for compatibility with ISO-8601 instead (ref ISO8601:2004 section 4.3.3 clause d).