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

I am trying to do a basic comparison of two dates in Perl. The current DateTime and elapsed time are correct, but subtraction gives incorrect results. The difference should be ~ 24 hours, but 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 
+6
source share
2 answers

Two time points are in different time zones. Therefore, the difference is actually 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 UTC time, and $now is in any time zone your environment thinks. To fix this, you need to decide which time zone you want.

+9
source

As DeVadder has already pointed out, this is because Time::Piece uses UTC for parsed time by default.

Assuming you want everything done using localtime , you really can encourage the parsed time to inherit your timezone from local: / p>

 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 
+2
source

All Articles