Tcl script to calculate a duration

Viewed 41

I need to create a script whithin I can calcute a durations here an example :

assign duration1 5.hours
assign duration2 4.minutes
assign duration3 10.seconds
assign seconds [calc_duration [getVar duration1] + [getVar duration2] + [getVar duration3]]*

I want to get as a respons (seconds) for the example I would have "18250" seconds.

can you please help me with this.

Thanks.

1 Answers

The clock add command can do calculations with durations, but it needs a base time to work with. That's important because, for example, not all months are the same number of days long, and not all days are the same number of hours because of DST rules (which are themselves not the same every year). If you're only working with the small units and not too many of them, you can ignore this and use 0 (the start of the Unix epoch) as the base time.

set seconds [clock add 0 5 hours 4 minutes 10 seconds]

But if you're working with longer amounts of time, you'll need to be more careful. clock add still has the tools, but you'll have to choose the base timestamp correctly and specify your locale of interest.

# You're really supposed to scan with a format, but I'm lazy
set baseTimestamp [clock scan "4/4/2022 10:30 EST"]
set timezone :America/New_York;   # EST/EDT
set timeBits {5 months 4 days 3 hours 2 minutes 1 second}

# Do the time arithmetic
set targetTimestamp [clock add $baseTimestamp {*}$timeBits -timezone $timezone]

# Convert into an elapsed number of seconds
set seconds [expr {$targetTimestamp - $baseTimestamp}]
# 13575721 seconds is a fair while...
Related