The following snippet turns a number of seconds to a compact string representing the equivalent amount of seconds in weeks, days, hours, minutes and seconds. This is useful for reporting elapsed time in an easily-graspable human-readable format (just how many weeks or days 123 456 789 seconds anyway)?
Here are some examples
12 12s 60 1m0s 3600 1h0m0s 3601 1h0m1s 3661 1h1m1s 10800 3h0m0s 86401 1d0h0m1s 123456789 204w0d21h33m9s
The code has a rather pleasing symmetry.
sub wdhms { my( $weeks, $days, $hours, $minutes, $seconds, $sign, $res ) = qw/ +0 0 0 0 0/; $seconds = shift; $sign = $seconds == abs $seconds ? '' : '-'; $seconds = abs $seconds; ($seconds, $minutes) = ($seconds % 60, int($seconds / 60)) if $sec +onds; ($minutes, $hours ) = ($minutes % 60, int($minutes / 60)) if $min +utes; ($hours, $days ) = ($hours % 24, int($hours / 24)) if $hou +rs; ($days, $weeks ) = ($days % 7, int($days / 7)) if $day +s; $res = sprintf '%ds', $seconds; $res = sprintf "%dm$res", $minutes if $minutes or $hours or $days +or $weeks; $res = sprintf "%dh$res", $hours if $hours or $days +or $weeks; $res = sprintf "%dd$res", $days if $days +or $weeks; $res = sprintf "%dw$res", $weeks if + $weeks; return "$sign$res"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Formatting elapsed time
by Hofmator (Curate) on Sep 06, 2001 at 17:34 UTC | |
by grinder (Bishop) on Sep 06, 2001 at 17:38 UTC | |
Re: Formatting elapsed time
by m-rau (Scribe) on Feb 10, 2005 at 17:48 UTC | |
by 5mi11er (Deacon) on Feb 10, 2005 at 19:57 UTC |
Back to
Cool Uses for Perl