batkins has asked for the wisdom of the Perl Monks concerning the following question:

Is there any module or builtin that can be used to convert a given time interval (in seconds) into hours, minutes, days, etc?
milkbone - perl/tk instant messaging - it's the only way to fly

You know anyone who'll debug two million lines of code for what I get this job?
- Dennis Nedry

Replies are listed 'Best First'.
Re: conversion of time intervals
by gellyfish (Monsignor) on Jun 23, 2003 at 11:14 UTC
Re: conversion of time intervals
by Skeeve (Parson) on Jun 23, 2003 at 11:19 UTC
    localtime and gmtime will do.
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = gmtime($sec);
    At least it will gve you:
    • $hours, $minutes, $seconds
    • days as long as it's less than 365 (in $yday)
    • years, if you subtract 70 from $year
    You'll have to take care of leap years of course.
Re: conversion of time intervals
by ctilmes (Vicar) on Jun 23, 2003 at 11:15 UTC
    Date::Manip will do this. Read all the caveats in the docs though...
Re: conversion of time intervals
by husker (Chaplain) on Jun 23, 2003 at 13:51 UTC
    Actually, some Monks and I have had this discussion before.

    Here's what I ended up using:

    ## ## Convert an integer number of seconds into a ## formatted ddd:hh:mm:ss string. ## sub s2d { use integer; my $s = shift; return sprintf ":%02d", $s if $s < 60; my $m = $s / 60; $s = $s % 60; return sprintf "%02d:%02d", $m, $s if $m < 60; my $h = $m / 60; $m %= 60; return sprintf "%02d:%02d:%02d", $h, $m, $s if $h < 24; my $d = $h / 24; $h %= 24; return sprintf "%d:%02d:%02d:%02d", $d, $h, $m, $s; } ## ## Is year a leap year? ## sub is_leap { my ($yy); ($yy)=@_; if ($yy % 4 == 0 and ($yy % 100 != 0 or $yy % 1000 == 0)) { return 0; } else { return 1; } }
Re: conversion of time intervals
by erasei (Pilgrim) on Jun 23, 2003 at 13:41 UTC
    While this might not be exactly what you asked for (a pre-built command), I use these few subs quite a bit in my time code. Might be of help to you, or others.
    sub hms { my ($s) = shift; my ($h, $m); $m = int($s / 60); $s = $s % 60; $h = int($m / 60); $m = $m % 60; if ($s > 0) { $m++; } if ($m == 60) { $m=0; $h++; } sprintf("%s:%02d:%02d",comma($h),$m, %s); } # Convert a number to a standard english comma'd string. # From "Programming Perl". sub comma { local ($_) = @_; 1 while s/(.*\d)(\d\d\d)/$1,$2/; $_; }