Version 8 of Formatting durations

Updated 2002-11-11 18:13:10

The following proc converts an integer number of seconds to culture-dependent units (days, hrs, mins, secs) specification. From a news:comp.lang.tcl posting by David Gravereaux:

Here's a duration proc I wrote that should give you a better sense of what I think you're asking 'clock format' for:

 % proc duration { int_time } {
     set timeList [list]
     foreach div {86400 3600 60 1} mod {0 24 60 60} name {day hr min sec} {
         set n [expr {$int_time / $div}]
         if {$mod > 0} {set n [expr {$n % $mod}]}
         if {$n > 1} {
             lappend timeList "$n ${name}s"
         } elseif {$n == 1} {
             lappend timeList "$n $name"
         }
     }
     return [join $timeList]
 }
 % duration 67
 1 min 7 secs

For a version of the same that handles floats and avoids OCTAL, see:

 http://inferno.slug.org/cgi-bin/wiki/duration

 * David Gravereaux *
 Tomahawk Software Group

Updated by DKF


Culture-independent hh:mm:ss notation by RS:

 proc hh:mm:ss {secs} {
        set h [expr {$secs/3600}]
        incr secs [expr {$h*-3600}]
        set m [expr {$secs/60}]
        set s [expr {$secs%60}]
        format "%02.2d:%02.2d:%02.2d" $h $m $s
 }
 hh:mm:ss 67
 00:01:07

Oops, forget it. Tcl has it built in (if you force GMT):

 clock format 67 -gmt 1 -format %H:%M:%S   ;#RS
 00:01:07

Bah! That chokes on Octal and fractional seconds, Richard!! - RS: I'm not sure whether we're talking about the same - the original question was to format an integer number of seconds into hour/min/sec format. Fractionals are excluded by the "integer", but octals just work as always:

 % clock format 012345 -gmt 1 -format %H:%M:%S   
 01:29:09

You can redeem yourself by making spamMap work, however...

Or octals don't work as always, depending on your perspective... I suppose we are talking about two different things; I added support for decimal seconds and stripping the leading 0 from octals because my user base required it.


KBK All of the above have problems with dealing with units of variable length. Consider the problem of "what's the day one month after 30 January," or even "what's the time at one day after noon on the day before the clocks go to Daylight Saving Time (Sommerzeit)." For that sort of problem, you need to compute the years, months, days, etc. between two dates.