Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 756
user1768233 Avatar asked Apr 15 '14 06:04

user1768233


1 Answers

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.

like image 116
DeVadder Avatar answered Nov 14 '22 09:11

DeVadder