我试图在Perl中对两个日期进行基本比较.当前日期时间和过去时间是正确的,但减法给出不正确的结果.差异应该是~24小时,但它返回~13小时.知道为什么以及如何解决它?谢谢.
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
解决方法
这两个时间点位于不同的时区.所以差异实际上是正确的.你可以看到
print $now->tzoffset,"\n"; # 7200 (I am in UTC +2 hence have 7200s offset) print $then->tzoffset,"\n"; # 0
所以基本上$then是UTC时间,而$now现在是你的环境认为的时区.要解决这个问题,您需要决定所需的时区.