In Twig, how do I compare if the date is within X days?

I use a branch to indicate a row in the table if the date associated with this row is less than 30 days.

The Twig documentation states that to compare two date objects, you must first convert the object to a date, and then do the comparison in this way:

{% if date(yourDate) < date(-'30days') %} ... {% endif %}

However, it does not indicate how to pass the date format for the left side of the comparison, I understand that the Twig date function is a kind of wrapper for the PHP date.

In PHP, I usually called:

$myDate = \DateTime::createFromFormat("m/d/Y", $myDate);

but in Twig, there seems to be no way to specify the original date format to convert it to another format, or at least to the documentation.

Here is what I tried:

{% if date(d.LastDate) > date('-30days') %}...{% endif %}

{% if d.LastDate | format("Ymd") > date('-30days') %}...{% endif %}

{% if date("m/d/Y", d.LastEmailSentDate) > date('-30days') %}...{% endif %}

These conditions and their variants 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 returns a date in the format: m/d/Y , and I just want to mark this line if this date is less than 30 days.

+6
source share
3 answers

Compare two dates, getting the number of seconds since Unix Epoch (PHP U date format)

 {% if d.LastDate|date("U") > "-30 days"|date("U") %} <p>Less than 30 days old</p> {% endif %} 
+17
source

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

+13
source

Since PHP 5.3 there is a higher accuracy.

 {# endDate and startDate are strings or DateTime objects #} {% set difference = date(endDate).diff(date(startDate)) %} {% set leftDays = difference.days %} {% if leftDays > 30 %} Less than 30 days old {% else %} More than 30 days old {% endif %} 

Explanation:

PHP 5.3 DateTime object has a diff() method that returns a DateInterval with a difference of results between endDate and beginDate Twig

The twig date function always returns a DateTime object, so we can call the diff method

Finally, we can access the properties of the DateInterval object or format it using the Twig date filter.

Note. There is no need for a wrap endDate or startDate with a date function if the variable is already a DateTime object.

Note2: DateTime used here as a synonym for DateTimeInterface .

+3
source

Source: https://habr.com/ru/post/957351/


All Articles