homer homer - 3 years ago 333
Twig Question

Displaying a DateInterval in Twig

I'm trying to display a DateInterval in Twig using the following code:

{{ event.endTime.diff(event.startTime)|date("i's''") }}


where
event
is an Entity who get 2 DateTime object:
endTime
and
startTime
. With that command I've got this output:

i's''


Instead of
min'sec''
like
08'15''


It is said in the date doc that


The date filter accepts [...] DateInterval instances


This work to display min and sec from a date object.

Note that doing:
{{ (event.endTime.diff(event.startTime))|date("i's''") }}
doesn't change anything

I also tried
{{ date(event.endTime.diff(event.startTime))|date("i's''") }}
but this lead to an exception
Object of class DateInterval could not be converted to string


I've also seen
time_diff
from Twig Extensions but this return a string (
in
or
ago
) instead of a Date object, then I can't display it as I want.

Let me know if you need more informations. Thank you for your help.

Answer Source

As @Yoshi said:

(new \DateTime('tomorrow'))->diff(new \DateTime('now'))->format("i's''") also gives "i's''", so I'd say this is not a twig-thing. From the manual:

"The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%)."

So to fix my proble I just had to do:

{{ event.endTime.diff(event.startTime)|date("%i'%s''") }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download