Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

RE: Convert seconds into a formatted ddd:hh:mm:ss string

by ncw (Friar)
on Aug 31, 2000 at 14:20 UTC ( [id://30489]=note: print w/replies, xml ) Need Help??


in reply to Convert seconds into a formatted ddd:hh:mm:ss string

You could do this with an amusing (ab)use of gmtime thus :-
$string = join ":", map { sprintf "%02d", $_ } (gmtime($seconds))[7, +2,1,0];
Or perhaps slightly more sanely as
$string = sprintf "%02d:%02d:%02d:%02d", (gmtime($seconds))[7,2,1,0] +;
If you want to strip the string then run this on it
$string =~ s/\G00://g;
This regexp idea came from merlyn via Effective Perl

Replies are listed 'Best First'.
RE: RE: Convert seconds into a formatted ddd:hh:mm:ss string
by merlyn (Sage) on Aug 31, 2000 at 14:46 UTC
    Yes yes yes. This is what I was getting at when I said earlier (in the chatterbox) that the code looked "far too regular". ncw, you've done a nice job abstracting the problem.

    Also, the use of sprintf there to add the leading 0 is much more perl-ish than the few odd snippets I've seen in this thread of:

    $var = "0$var" if $var < 10;
    Maybe it's because I first saw that weird-looking code in a Matt Wright script, and it's now tainted me. It scares me to think what other horrors people have now learned from Matt Wright scripts. {grin}

    I think for me the problem is that the non-sprintf solution does not scale well. For example, what if you wanted three digits? Do you add another test?

    $var = $var < 10 ? "00$var" : $var < 100 ? "0$var" : $var;
    No, if I saw code like that in a code review, I'd flag that immediately with "this must be changed before deployment: unmaintainable".

    So, get cozy with sprintf: it solves many problems (including the rounding problem discussed a few days ago).

    -- Randal L. Schwartz, Perl hacker

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://30489]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-04-19 06:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found