DEV Community

Discussion on: Daily Challenge #21 - Human Readable Time

Collapse
 
choroba profile image
E. Choroba
#!/usr/bin/perl
use warnings;
use strict;

my @UNITS;
unshift @UNITS, $_ * ($UNITS[0] || 1) for 1, 60, 60, 24, 365;
my @NAMES = qw( year day hour minute second );

sub format_duration {
    my ($s) = @_;
    my @out;
    for (@UNITS) {
        push @out, int($s / $_);
        $s = $s % $_;
    }
    @out = map $out[$_] ? "$out[$_] $NAMES[$_]"
        . ("", 's')[ $out[$_] > 1 ]: (), 0 .. @NAMES;
    return join ' and ', join(', ', @out[0 .. $#out - 1]) || (), $out[-1];
}


use Test::More tests => 5;

is format_duration(62), '1 minute and 2 seconds';
is format_duration(3662), '1 hour, 1 minute and 2 seconds';
is format_duration(66711841),
    '2 years, 42 days, 3 hours, 4 minutes and 1 second';
is format_duration(31539601), '1 year, 1 hour and 1 second';
is format_duration(120), '2 minutes';