in reply to Calculate "friendly" duration from # of seconds
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!
|
|---|