Learn how to format a datetime object to ISO 8601 format with twig easily.

ISO 8601 describes an internationally accepted way to represent dates and times using numbers. The format of a datetime in ISO8601 should have the following format:

2016-04-27T18:30:00-05:00 (Year-Month-Day-T-Hours-Minutes-Seconds-Timezone)

To format a datetime with twig is very easy and you don't need to write it by yourself, just use the c format which is predefined with twig.

{{"now"|date("c")}}
{#Which outputs something like : 2016-04-29T15:47:28+02:00 #}

However if for some reason the previous line doesn't work for you, you can still format manually with all the parameters using :

{{"now"|date("Y-m-d\\TH:i:sP")}}
{#Which outputs something like : 2016-04-29T15:47:28+02:00 #}

You'll use this format for example in the google rich snippets. You can test the following TwigFiddle to see a working example:

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors