in reply to Converting Seconds to Nice Format
I'm surprised that everyone is computing 60*60*24*365 instead of computing the values in an order that makes this calculation unnecessary [ update: except for the above by Dr. Mu which was entered while I typed this one :) ].
prints#!/usr/bin/perl -wl use strict; print join "\n", map { secs2str( $_ ) } <DATA>; exit( 0 ); { my( @div, @unit ); BEGIN { @div= ( 60, 60, 24, 365 ); @unit= qw( second minute hour day year ); } sub secs2str { my( $left )= @_; my @val= ( map( { my $unit= $left; $left= int( $left / $_ ); $unit -= $left * $_; } @div ), $left ); @val= map { 0 == $val[$_] ? () : "$val[$_] $unit[$_]" . ( 1 == $val[$_] ? "" : "s" ) } reverse 0..$#val; return 0==@val ? "now" : 1==@val ? $val[0] : 2==@val ? join( " and ", @val ) : join ", ", @val[0..$#val-1], "and $val[-1]"; } } __END__ 0 1 10 100 1020 10000.5 100840 1000900 10000000 100000020.5 1000000000
I'd put fractions other than 0.5 in but then I'd have to include logic to remember number of digits after the decimal place and use that to trim the output (or just show ugly output). (: - tye (but my friends call me "Tye")now 1 second 10 seconds 1 minute and 40 seconds 17 minutes 2 hours, 46 minutes, and 40.5 seconds 1 day, 4 hours, and 40 seconds 11 days, 14 hours, 1 minute, and 40 seconds 115 days, 17 hours, 46 minutes, and 40 seconds 3 years, 62 days, 9 hours, 47 minutes, and 0.5 seconds 31 years, 259 days, 1 hour, 46 minutes, and 40 seconds
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: (tye)Re: Converting Seconds to Nice Format
by snax (Hermit) on Nov 13, 2000 at 17:27 UTC | |
by tye (Sage) on Nov 13, 2000 at 22:11 UTC | |
by snax (Hermit) on Nov 14, 2000 at 13:20 UTC | |
by tye (Sage) on Nov 14, 2000 at 20:22 UTC |