6

How can I call the 'time_diff' function In Twig

The code

{{ post.created_at|time_diff }}

Output

The filter "time_diff" does not exist
BENARD Patrick
  • 30,363
  • 16
  • 99
  • 105
hassen zouari
  • 161
  • 3
  • 11

4 Answers4

20

If you're using Symfony 2,

And want to use some of the native twig extension

You have to declare as service something like :

services:
    twig.extension.date:
       class: Twig_Extensions_Extension_Date
       tags:
            - { name: twig.extension }
BENARD Patrick
  • 30,363
  • 16
  • 99
  • 105
3

At first you need:

composer require twig/extensions

Then you need to register Date extension:

$twig->addExtension(new Twig_Extensions_Extension_Date());

After that you could use time_diff filter. All in docs

Ilya Yarkovets
  • 820
  • 4
  • 12
3

I suggest You to use the KnpTimeBundle

So you can simply compare with the current date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(myEntity.getMyTimeField) }}

This compare with the another date:

{# Returns something like "3 minutes ago" #}
{{ time_diff(myEntity.getMyTimeField , to ) }}

The translation is enabled by default, simply review the translations files or add as you need.

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
  • I've set the locale as IT, but the translation isn't done. Any suggestion? – Aerendir Dec 13 '15 at 20:20
  • 1
    Using https://github.com/KnpLabs/KnpTimeBundle seems to be the best solution for today (symfony 5). No customization needed just run:composer require knplabs/knp-time-bundle and use it {{ date|ago }} – Marcin Oct 10 '20 at 14:38
  • Thanks @marcin to confirm after five years that the solution is still valid :) – Matteo Oct 10 '20 at 17:41
1

Did you add the date extension?

Add the following line before using this formatting:

$twig->addExtension(new Twig_Extensions_Extension_Date());
Jerodev
  • 32,252
  • 11
  • 87
  • 108