1

I'm converting an integer to a time format in the Twig template system. So that total duration of seconds is converted to hh:mm:ss.

Here is an example to how i convert hours:

{% filter round(0, 'floor') %}{{ agent.TotalCallDuration/3600 }}{% endfilter %}

Now I have to add leading zero to the hours if less than 10. I tried:

{% filter round(0, 'floor')|format('%02d') %}{{ agent.TotalCallDuration/3600 }}{% endfilter %}

But no luck..

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
johnohod
  • 494
  • 5
  • 19

1 Answers1

0

Use the date filter with timezone argument set to false:

{{ agent.TotalCallDuration | date("H:i:s", false) }}

For values bigger than 24 hours

The above solution works only if the number of seconds is lesser than 86400 seconds (24 hours). For bigger values, I would write a simple filter using the gmdate function1, e.g.:

$twig->addFilter(new Twig_Filter('duration', function ($x) {
    return $x >= 86400 ? gmdate('d:H:i:s', $x - 86400) : gmdate('H:i:s', $x);
}));

where $twig is an instance of Twig_Environment.

Usage:

{{ agent.TotalCallDuration | duration }}

Another example where "days" are expressed in hours (hh:mm:ss):

$twig->addFilter(new Twig_Filter('duration', function ($x) {
    if ($x < 86400) {
        return gmdate('H:i:s', $x);
    }

    $hours = gmdate('G', $x);
    $days = (gmdate('d', $x) - 1) * 24 + $hours;
    return $days . gmdate(':i:s', $x);
}));

1 Idea is taken from this answer.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
  • On closer review. It doesn't work. I have an example where agent.TotalCallDuration = 336651, that is converted to: 21:30:51, when it should have been well above than 95 hours. – johnohod Sep 29 '17 at 08:20