Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't control how hours, minutes seconds are formatted using Perl's Datetime::Format::Duration

Tags:

perl

The following snippet calculates the duration between two times, but I don't understand how to control the formatted output. In this example, the duration is not output as 00 days, 22 hours, 44 minutes, 03 seconds. Instead, it is output as 00 days, 00 hours, 1364 minutes, 03 seconds. How can I control this?

#!/usr/bin/perl
use strict;
use DateTime;
use DateTime::Format::Strptime;
use DateTime::Format::Duration;
use feature 'say';

my $parser = DateTime::Format::Strptime->new(
            pattern =>'%Y-%m-%d %H:%M:%S',
            time_zone => 'UTC'
);

my $startDateTime = $parser->parse_datetime('2013-10-13 05:59:44');
my $stopDateTime =  $parser->parse_datetime('2013-10-14 04:43:47');
my $duration = DateTime::Duration->new($stopDateTime-$startDateTime);

my $format = DateTime::Format::Duration->new(
    pattern => '%d days, %H hours, %M minutes, %S seconds'
);

say $startDateTime;
say $stopDateTime;
say $format->format_duration($duration);

Resulting Output:

2013-10-13T05:59:44
2013-10-14T04:43:47
00 days, 00 hours, 1364 minutes, 03 seconds
like image 403
prh Avatar asked Jan 20 '26 01:01

prh


1 Answers

my $format = DateTime::Format::Duration->new(
    pattern   => '%d days, %H hours, %M minutes, %S seconds',
    normalize => 1,
);

say $format->format_duration($duration);

Or to avoid the leading zeros:

say sprintf "%d days, %d hours, %d minutes, %d seconds",
   $duration->in_units(qw( days hours minutes seconds ));
like image 92
ikegami Avatar answered Jan 22 '26 19:01

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!