hh:mm:ss between 2 dates

S

simulant

I must have read about 150 different threads on how to perform date
arithmetic in Perl, but I am still not quite sure the best route to
take. When it comes to date arithmetic, it seems there are a lot of
frustrated programmers, from what I read in the posts!

Ok, here's the deal ... I have 4 dates:

$pstart = "12/08/06 14:00:00";
$pend = "12/08/06 14:00:02";
$qstart = "12/08/06 14:00:02";
$qend = "12/08/06 14:00:12";

I want to essentially do this ... pseudocode follows:

$total_time = ($pend - $pstart) + ($qend - $qstart);

I want $total_time to be in the format "hh:mm:ss"

I have been trying to use DateCalc from Date::Manip to help me out
here, but I'm stuck. I have the results of DateCalc, but how do I add
them together, or is there an overall better way to do this?:

$ptotal = DateCalc(ParseDate($pstart), ParseDate($pend)); # returns
"+0:0:0:0:0:0:2"
$qtotal = DateCalc(ParseDate($qstart), ParseDate($qend)); # returns
"+0:0:0:0:0:0:10"

So, in this case, I want to return the sum of the 2 above totals in
this format: "00:00:12"
 
U

usenet

simulant said:
$qtotal = DateCalc(ParseDate($qstart), ParseDate($qend)); # returns
"+0:0:0:0:0:0:10"

What you've got there is a "date delta". You can parse out the various
fields of interest with something like this:

print Delta_Format($qtotal, 0, "%hv:%mv:%sv");

That prints out the value (the 'v' part of the string) for the hour,
minute, and seconds (the 'h', 'm', and 's' parts of the string). It
separates the fields with ':'. The '0' in the middle is the decimal
precision, and seems to be a requried parameter (even if it's zero).

However, unlike Date::Manip's UnixDate routine, the Delta_Format
routine does not offer output options for leading zeros, so this
statement would yield:

0:0:10

I suppose you could do something really mean and ugly like this:

print join ":",
map{sprintf("%02d",Delta_Format($qtotal,0,"%${_}v"))} qw{h m s};

But stick around, because somebody will probably come along and show
you a (much) better way.
 
U

usenet

simulant said:
So, in this case, I want to return the sum of the 2 above totals in

To combine date deltas, just use DateCalc:

my $total_delta = DateCalc($qtotal, $ptotal);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top