How to Format Date/Time in ISO-8601 Using the PHP DateTime Class?

You can format a date/time in the ISO-8601 format using the DateTime class in PHP in the following ways:

Using DateTime::ATOM

The pre-defined constant DateTime::ATOM can be used to format date/time in the ISO-8601 format. You can use it in the following way:

$datetime = new DateTime('2021-01-03 02:30:00', new DateTimeZone('Europe/Berlin'));

echo $datetime->format(DateTime::ATOM); // output: '2021-01-03T02:30:00+01:00'

This constant is actually defined in DateTimeInterface (as 'Y-m-d\TH:i:sP') so it can be used with any date/time class that implements the interface. Alternatively, you may also use the global constant DATE_ATOM.

There is also a DateTime::ISO8601 format (and its global constant variant DATE_ISO8601) which is not compatible with ISO-8601, and exists for backward compatibility reasons. You should use DateTime::ATOM instead. To learn more about this, you can check out our post about the differences between DateTime::ATOM and DateTime::ISO8601.

Using the c Format Character

Another way to format the date/time in the ISO-8601 format is to use the "c" formatting character like so:

$datetime = new DateTime('2021-01-03 02:30:00', new DateTimeZone('Europe/Berlin'));

echo $datetime->format('c'); // output: '2021-01-03T02:30:00+01:00'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.