how to check if today is between two dates in Twig?

17,832

Solution 1

According to the TWIG manual, you can use date function. If no argument is passed, the function returns the current date.

So your code might look like this in TWIG:

{% if date(room.price_start_date) < date() and date(room.price_end_date) > date() %}
  {# condition met #}
{% endif %}

Solution 2

Use \DateTime instances to compare dates in Twig (as well as PHP).

What is wrong?

date('Y-m-d') function returns a formatted date string.

So, you should to change it to $today = new \DateTime('today'); and pass this instance to Twig template or use date() Twig function directly in your condition.

The price_start_date and price_end_date I get them from database and their columns' type is Date.

Assuming that these two (room.price_start_date and room.price_end_date) are instances of \DateTime, then your Twig code should work fine.

Share:
17,832
Ahmed Essam
Author by

Ahmed Essam

Updated on June 18, 2022

Comments

  • Ahmed Essam
    Ahmed Essam almost 2 years

    I'd like to check if today's date is between two dates from the database. Here's my code.

    {% if today < room.price_start_date and today > room.price_end_date %}
    <a href="{{'/'|app}}/book/{{room.id}}"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
    {% else %}
    <a href="{{'/'|app}}/contact"><button type="button" class="btn btn-default btn-xs">Book this room</button></a>
    {% endif %}
    

    The today variable gets its value from this code:

    $todayDate = date('Y-m-d');
    $this['today'] = date('Y-m-d', strtotime($todayDate));
    

    The price_start_date and price_end_date I get them from database and their columns' type is Date

    Any idea how to check if today is between room.price_start_date and room.price_end_date in Twig?

  • Ahmed Essam
    Ahmed Essam over 7 years
    Actually I changed the comparison signs to ` {% if date(room.price_start_date) < date() and date(room.price_end_date) > date() %} ` and worked. Many Thanks !
  • Farside
    Farside over 7 years
    @AhmedEssam, thanks, you are right, I updated the comparison signs the right way. Feel free to accept the answer, and hope it helps to someone else as well!
  • Will B.
    Will B. over 5 years
    It should be noted that YYYY-MM-DD date strings (date('Y-m-d')) are correctly comparable in PHP 3v4l.org/bCfZv and twig twigfiddle.com/opjcw8
  • Mbotet
    Mbotet about 4 years
    This will only work if both start and end are set. If any of those are "open" or null wont work correctly.