Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localize dateinterval in Twig

Tags:

twig

symfony

I've a entity method returning a PHP DateInterval between a DateTime property of this entity and now, to know how many time left before this datetime.

I want to display this interval in Twig so I used something like that:

{{ myEntity.getTimeRemaining | date("%D days %H Hours %i Mins ") }}

It's working fine.

Now, how can I localize this format? (and eventually consider the plural) I've found transchoice method but it's seem to be only to localize date, not a interval.

like image 923
Yoann Augen Avatar asked Sep 28 '22 10:09

Yoann Augen


1 Answers

You can use the KnpTimeBundle

I think this bundle can simplify your implementation, so you can directly dump the time difference between now without pass thru a DateInterval, you can simply 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

like image 117
Matteo Avatar answered Oct 13 '22 11:10

Matteo