10

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.

homer
  • 882
  • 8
  • 23
  • 4
    `(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](https://secure.php.net/manual/en/dateinterval.format.php): *"The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%)."* – Yoshi Jan 20 '17 at 09:54
  • Thank you very much, In fact I had to add `%` before `i` and `s` – homer Jan 20 '17 at 15:29

2 Answers2

9

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''") }}
homer
  • 882
  • 8
  • 23
0

When putting in the method format the parameters 'i' and 's' in lowercase, when the value to be displayed is less than 10, put a single digit.

Example if you need to display the time of 5 minutes and 2 seconds by showing a leading zero (05:02). You have to capitalize the parameters, it would be like this:

{{ event.endTime.diff(event.startTime)|date("%I:%S") }}

The allowed parameters can be found in: DateInterval format

Jaime Roman
  • 749
  • 1
  • 11
  • 26