Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 202
Ahmed Essam Avatar asked Dec 26 '16 16:12

Ahmed Essam


2 Answers

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 %}
like image 84
Farside Avatar answered Nov 20 '22 12:11

Farside


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.

like image 33
yceruto Avatar answered Nov 20 '22 10:11

yceruto