Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: How do I add two or more quantities of time - HH:MM:SS ?

by mojotoad (Monsignor)
on Oct 24, 2002 at 19:40 UTC ( [id://207830]=note: print w/replies, xml ) Need Help??


in reply to How do I add two or more quantities of time - HH:MM:SS ?

This question, as stated, does not make much sense. What does it mean to add two times off of the clock? (see below if you just meant time segments expressed as hours, minutes, and seconds)

Perhaps you meant you wanted the difference between two times. In that case, Time::Piece is your friend.

First, you want to make your time pieces. These are generated via localtime(), gmtime, new(), or strptime(). If you happen to have seconds since the epoch, you can generate arbitrary time pieces with gmtime or localtime. Otherwise, if you are starting with HH::MM::SS you can use strptime() like so:

use Time::Piece; $t = Time::Piece->strptime('%T', $time_string);

Once you have your time pieces, you can find the difference by subtracting them directly. This generates a Time::Seconds object -- since this is the difference between two dates, it represents no particular date. Rather, it represents the number of seconds between to points in time. It can be displayed in a variety of convenient formats (see the pod).

$seconds = $t2 - $t1; print "Diff (secs): ", $seconds->seconds, "\n";

Additionally, if you want to add two chunks of time as expressed with hours, minutes, and seconds (as you might have been asking), you will want to express them as Time::Seconds objects using strptime. Then you can proceed normally with addition:

$total_secs = $s2 + $s1; print "Secs: ", $total_secs->seconds, "\n";

Matt

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (None)
    As of 2024-04-25 01:05 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found