Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract two HH:MM:SS times from each other in Perl?

Tags:

time

perl

I need to subtract one time from another using Perl. Both times are in the HH:MM:SS format.

I could simply split the time strings on the colons, and then perform the maths on each set of digits, which is relatively straightforward:

$seconds_passed = $seconds_later - $seconds_earlier;
if ($seconds_passed < 0) { $seconds_passed = 60 - abs($seconds_passed); }

and so on for the minutes and hours, and then get calculate the total time passed by converting each result to seconds and adding them up. The second line is to handle cases where the later number is actually higher, say the first time was 23:58:59 and the second was 23:59:09, the actual number of seconds that have passed is 10, but the calculation would give 09-59 = -50, so subtracting the positive form of that (50) from 60 gives the correct result.

In this case I'm looking for the simplest, smallest solution possible (trying to avoid the use of large and complex modules where possible), so this may be the solution I go with anyway, but wondering if there's a standard / built in way of doing this kind of thing?

like image 882
Pyromancer Avatar asked Nov 04 '13 12:11

Pyromancer


1 Answers

Time::Piece has been part of the core Perl distribution since Perl 5.9.5:

use strict;
use warnings;
use Time::Piece;

my $t1 = Time::Piece->strptime( '23:58:59', '%H:%M:%S' );
my $t2 = Time::Piece->strptime( '23:59:09', '%H:%M:%S' );

print ( $t2 - $t1 ); # 10
like image 114
Zaid Avatar answered Oct 13 '22 19:10

Zaid