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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With