Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subtract dates in twig?

Tags:

twig

{%for mat in setQuery %}
   {% set datePost = mat.data_criacao|date('d-m-Y') %}
   {% set today = "now"|date('d-m-Y') %}
   {{today- datePost}}
{% endfor %}

datePost = 17-04-2015 today = 06-05-2015

the example above returns it: -11

like image 248
Gabriel Schmidt Cordeiro Avatar asked May 06 '15 15:05

Gabriel Schmidt Cordeiro


People also ask

How do you compare two dates in twig?

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.


2 Answers

The issue was resolved with the following code:

{% set datePost = mat.data_criacao|date('d-m-Y') %}
{% set today = "now"|date('d-m-Y') %}
{% set difference = date(today).diff(date(datePost))%}
{% set leftDays = difference.days %}
{% if datePost == today %}
      1 day
{% else %}
    {{ leftDays }}
{% endif %}          
like image 134
Gabriel Schmidt Cordeiro Avatar answered Oct 01 '22 08:10

Gabriel Schmidt Cordeiro


You must write your custom twig extension:

You must write a twig function as described here with the following code for make diff via php function:

$calcFrom = $from;

$calcTo = $to;
$now->diff($calcFrom)->format("%a")

And make it available via a Twig extension.

If you are using symfony2 framework You can use the KnpTimeBundle

In the Twig: This compare with the current date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(form) }}

This compare with the another date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(form , to ) }}

Hope this help

like image 37
Matteo Avatar answered Oct 01 '22 08:10

Matteo