I'm using twig to flag a row in a table, if the date associated with that row is less than 30 days old.
Twig's documentation states that to compare two date objects, you have to convert the object to date first, and then make a comparison this way:
{% if date(yourDate) < date(-'30days') %} ... {% endif %}
However, it doesn't specify how to pass the date format for the left side of the comparison, I understand that Twig's date function is some sort of a wrapper for PHP's date.
In PHP I would usually call:
$myDate = \DateTime::createFromFormat("m/d/Y", $myDate);
but in Twig apparently there's no way to specify the original date's format in order to convert it to another format, or at least it's not in the documentation.
This is what I've tried:
{% if date(d.LastDate) > date('-30days') %}...{% endif %}
{% if d.LastDate | format("Y-m-d") > date('-30days') %}...{% endif %}
{% if date("m/d/Y", d.LastEmailSentDate) > date('-30days') %}...{% endif %}
Those conditions and their variations return the following exception in Symfony2:
An exception has been thrown during the rendering of a template
("DateTimeZone::__construct(): Unknown or bad timezone (---)")
My controller is returning a date in the format: m/d/Y
and I just want to flag that row if that date is less than 30 days old.
So that's how we can compare dates in Twig. The main thing is to get both dates in the same format and then compare. If you need specificity, you can use Epoch time; if you need less specificity, you can convert the date to a string and compare them that way.
Method 2: If both of the given dates are in different formats then use strtotime() function to convert the given dates into the corresponding timestamp format and lastly compare these numerical timestamps to get the desired result. echo "$date1 is older than $date2" ; ?>
Compare the two dates by getting the number of seconds since the Unix Epoch (PHP Date Format U
)
{% if d.LastDate|date("U") > "-30 days"|date("U") %}
<p>Less than 30 days old</p>
{% endif %}
Twig 1.6
supports date comparison.
{% if date(d.LastDate) > date("-30 days") %}
<p>Less than 30 days old</p>
{% endif %}
{% if date(d.LastDate) > date("now") %}
<p>Future date</p>
{% endif %}
http://twig.sensiolabs.org/doc/functions/date.html
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