Compare dates with Twig

Quentin Pleplé – 2011

Here is a trick to compare two dates in Twig. Convert them as string with the date filter, with first the year, then the month and finally the day:

myDate|date('Y-m-d')

Then, you can compare strings because the chronological order is the same than the lexicographical order:

{% if date1|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}

Tip. If you want to get the current date, you can give the string now to the date filter:

{% if "now"|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}
Feel free to ask questions right here ↓