perl - Why doesn't date.format() from Template::Plugin::Date return the duration I expect? -
i have duration in seconds i'm trying convert hh:mm:ss format template toolkit plugin template::plugin::date:
[% use date %] [% set tseconds = 478966 %] [% date.format(tseconds ,'%h:%m:%s') %]
this returns 13:02:46, expected return 133:02:46 (478966 seconds equal 133 hours, 2 minutes, , 46 seconds). there other way convert duration in seconds hh:mm:ss format using template toolkit?
there isn't plugin that, can write own function , pass in information hash, this
use strict; use warnings 'all'; use time::seconds; use template; $vars = { format_hms => \&format_hms, }; $tt = template->new; $tt->process(\<<end_template, $vars); [% set tseconds = 478966 %] [% format_hms(tseconds) %] end_template sub format_hms { $t = time::seconds->new(shift); $h = int $t->hours; $t -= $h * one_hour; $m = int $t->minutes; $t -= $m * one_minute; $s = int $t->seconds; sprintf "%d:%02d:%02d\n", $h, $m, $s; }
output
133:02:46
update
in case prefer make code available through custom plugin instead of passing subroutine reference in %vars
hash, here simple module allow that
package custom::template::plugin::duration; use strict; use warnings 'all'; use base 'template::plugin'; use time::seconds; sub format_hms { $self = shift; $t = time::seconds->new($_[0]); $h = int $t->hours; $t -= $h * one_hour; $m = int $t->minutes; $t -= $m * one_minute; $s = int $t->seconds; sprintf "%d:%02d:%02d\n", $h, $m, $s; } 1;
if save custom/template/plugin/duration.pm
in 1 of @inc
directories (the current working directory bet) can write code this
use strict; use warnings 'all'; use template; $tt = template->new( plugins => { duration => 'custom::template::plugin::duration', } ); $tt->process(\<<end_template); [% use duration %] [% set tseconds = 478966 %] [% tseconds %] equivalent [% duration.format_hms(tseconds) %] end_template
output
478966 equivalent 133:02:46
however there nothing different here except way template given access subroutine. underlying code identical
Comments
Post a Comment