10

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?

4

2 回答 2

16

Time::Piece自 Perl 5.9.5 以来一直是核心 Perl 发行版的一部分:

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
于 2013-11-04T13:43:30.647 回答
0

如果您只对几秒钟感兴趣,您可能只需使用:

use strict;
use warnings;
use Date::Parse;

my $diff = str2time('23:59:09') - str2time('23:58:59');
print "$diff\n";

Date::Parse 显然没有包含在 Perl 中,但我从未遇到过没有它的安装。

于 2013-11-05T19:08:45.453 回答