how to check if today is between two dates in Twig?
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
andprice_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.
Ahmed Essam
Updated on June 18, 2022Comments
-
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
andprice_end_date
I get them from database and their columns' type isDate
Any idea how to check if
today
is betweenroom.price_start_date
androom.price_end_date
in Twig? -
Ahmed Essam over 7 yearsActually 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 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. over 5 yearsIt 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 about 4 yearsThis will only work if both start and end are set. If any of those are "open" or null wont work correctly.