1 min read

How to compare dates in Twig

When comparing dates in a Twig template it's best to force formatting as a Unix timestamp in order for your > and < operations to work as expected.

Format a date as a timestamp in Twig

It's as simple as passing 'U' to the date filter formatter:

{{ "now"|date('U') }} will give you the timestamp you need 1727450061

While trying to do the same without the 'U' formatter will give you a default date formatting:

"now"|date() will produce "September 27, 2024 08:14"

Do the same for any date value you have from field output. A version of a date field output may look like this (your path to getting the date value may vary):

content.date[0]['end_date']['#markup']|date('U')

Comparing dates in Twig

With the examples above, comparing dates in a Twig file may look something like this:

{% if "now"|date('U') < content.date[0]['end_date']['#markup']|date('U') %}
  // Do something
{% endif %}