user1768233
user1768233

Reputation: 1461

Why does my Time::Piece code give strange results?

I am trying to do a basic comparison of two dates in Perl. The Current DateTime and the Past time are correct but the subtraction gives incorrect results. The Difference should be ~24 hours yet it returns ~13 hours. Any idea why and how to fix it? thanks.

use Time::Piece;

my $now = Time::Piece->new;
my $then = Time::Piece->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S");
my $diff = $now - $then;

print "Current time: $now\n";
print "Past time: $then\n";
print "Diff in Seconds:", $diff, "\n";
print "Pretty Diff:", $diff->pretty, "\n";

Results
------
Current time: Tue Apr 15 16:13:39 2014
Past time: Mon Apr 14 16:30:20 2014
Diff in Seconds:49399
Pretty Diff:13 hours, 43 minutes, 19 seconds

Upvotes: 6

Views: 220

Answers (2)

Miller
Miller

Reputation: 35198

As DeVadder has already stated, it's because Time::Piece defaults to UTC for parsed times.

Assuming you want everything done using your localtime, you can actually encourage the parsed times to inherit their Timezone from local like so:

use Time::Piece;

use strict;
use warnings;

my $now = Time::Piece->new;
my $then = localtime->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S");
my $diff = $now - $then;

print "Current time: $now\n";
print "Past time: $then\n";
print "Diff in Seconds:", $diff, "\n";
print "Pretty Diff:", $diff->pretty, "\n";

Outputs:

Current time: Tue Apr 15 17:12:08 2014
Past time: Mon Apr 14 16:30:20 2014
Diff in Seconds:88908
Pretty Diff:1 days, 0 hours, 41 minutes, 48 seconds

Upvotes: 2

DeVadder
DeVadder

Reputation: 1404

The two timepoints are in different timezones. So the difference is in fact correct. You can see that with

print $now->tzoffset, "\n";    # 7200 (I am in UTC +2 hence have 7200s offset)
print $then->tzoffset, "\n";   # 0

So basically $then is a UTC time while $now is in whatever timezone your environment thinks it is in. To fix that, you need to decide on what timezone you want.

Upvotes: 9

Related Questions