Version 5 of Formatting durations

Updated 2002-11-11 11:45:36

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

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.