Feed it a number of seconds (such as gleaned from time(), and it returns a string in the format of "4 days 1 hour 23 mins 5 secs".
sub duration { my $seconds = shift; my ($string, $flag); my @elements = ( { label => "years" }, { label => "days" }, { label => "hours" }, { label => "mins" }, { label => "secs" }, ); ( $elements[4]{value}, $elements[3]{value}, $elements[2]{value}, $elements[0]{value}, $elements[1]{value} ) = (gmtime($seconds))[0..2,5,7]; $elements[0]{value} -= 70; for my $element ( @elements ) { my $label = $element->{label}; $label = substr($label, 0, -1) if $element->{value} == 1; $string .= sprintf("%d $label ", $element->{value}, $flag = 1) if $element->{value} || $flag; } return $string }

Replies are listed 'Best First'.
Re: Calculate "friendly" duration from # of seconds
by EyeOpener (Scribe) on Aug 03, 2002 at 00:48 UTC
    A few notes on this:

    There were a couple specific things I wanted in the output which you may find odd in the code. First, I wanted to tackle singulars and plurals correctly (i.e. to say "1 hour" instead of "1 hours"). Also, I wanted the output to begin with the first needed element, and include all elements afterward. That is, I wanted "4 days 0 hours 0 mins 10 secs", instead of "4 days 10 secs" or "0 years 4 days 0 hours 0 mins 10 secs". I like this format, but it should be easy to change the code to suit your own tastes.

    One minor caveat: I threw the "years" in just for completeness, but I don't take daylight savings time or leap seconds into account, so of course they won't be entirely accurate. I use this for tracking the run time of scripts and reporting outage durations in a ping tool -- if you want to calculate the duration of something longer than a year, you probably shouldn't use this snippet! :)

    One major caveat: The Time::Duration module does pretty much this same thing and so much more (Update: or this, or this ... (sigh)). I wrote my snippet (and most of this writeup) before I discovered this module, otherwise I would have scrapped it. But what the heck, this is quick and easy, and someone out there might have some fun with this.

    Also, here's some code you can use to test this with, if you're still inclined:

    # change these to affect output my $y = 2; my $d = 0; my $h = 3; my $m = 1; my $s = 1; #don't change these my $ys = $y * 31536000; my $ds = $d * 86400; my $hs = $h * 3600; my $ms = $m * 60; my $seconds = $ys + $ds + $hs + $ms + $s; my ($sec, $min, $hour, $year, $day) = (gmtime($seconds))[0..2,5,7]; my $str = duration($seconds); print "Duration was $str\n";

    Have fun!

•Re: Calculate "friendly" duration from # of seconds
by merlyn (Sage) on Aug 03, 2002 at 05:58 UTC