#!/usr/bin/perlusewarnings;usestrict;my@UNITS;unshift@UNITS,$_*($UNITS[0]||1)for1,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;returnjoin' and ',join(', ',@out[0..$#out-1])||(),$out[-1];}useTest::Moretests=>5;isformat_duration(62),'1 minute and 2 seconds';isformat_duration(3662),'1 hour, 1 minute and 2 seconds';isformat_duration(66711841),'2 years, 42 days, 3 hours, 4 minutes and 1 second';isformat_duration(31539601),'1 year, 1 hour and 1 second';isformat_duration(120),'2 minutes';
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Discussion on: Daily Challenge #21 - Human Readable Time
For further actions, you may consider blocking this person and/or reporting abuse