menu

Questions & Answers

Timber (Wordpress Twig) - Display a list of events based on custom field "date" compared to current date

I try to display a list of events in separated lists when they are past or upcoming.

I use an ACF custom field called "date_event" and filled on every event post.

I just try to compare the date_event to the current date but it doesn't work and i don't get it.

I tried to print values of "datenow" and "date_event", they are differents, some are above datenow, some are beyond, but it doesn't fill the "upcoming list".

Hope someone could enlight me about this :-/

What i tried

     {# Displaying upcoming events only #}
       {% for post in posts %}
         {% if date(post.date_event) >= date() %}
           {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
         {% endif %}   
       {% endfor %}
   
     {# Displaying past events only #}
       {% for post in posts %}
         {% if date(post.date_event) < date() %}
           {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
         {% endif %}   
       {% endfor %}

Note : then i tried to add some |number_format or some datenow variable just to check...

That do nothing better

   {# Set current date #}
     {% set datenow = date()|date("Ymd")|number_format %}
     {{ datenow }}
      
     {# Displaying upcoming events only #}
       {% for post in posts %}
         {% if date(post.date_event)|date("Ymd")|number_format >= datenow %}
            {{ post.date_event|date("Ymd")|number_format }}
           {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
         {% endif %}   
       {% endfor %}
   
     {# Displaying past events only #}
       {% for post in posts %}
         {% if date(post.date_event)|date("Ymd")|number_format < datenow %}
         {{ post.date_event|date("Ymd")|number_format }}
           {% include ['tease-'~post.post_type~'.twig', 'tease.twig'] %}
         {% endif %}   
       {% endfor %}

I'm just trying to get it...

Answers(1) :

Convert the field 'post.date_event' to a date object, like this:

{% set event_date = post.date_event|date("U") %}

Then, you can compare it to the current date:

{% if event_date >= date("U") %}
Comments:
2023-01-25 00:15:06
OP was already casting the variables to a DateTime object using the date function, which should work as seen in the duped question, but you are comparing unix timestamps, which in itself is correct though