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?
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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With