2014-04-15 86 views
6

我想在Perl中做兩個日期的基本比較。當前日期時間和過去時間是正確的,但減法給出不正確的結果。差異應該是〜24小時,但它返回〜13小時。任何想法爲什麼以及如何解決它?謝謝。爲什麼我的Time :: Piece代碼給出奇怪的結果?

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 

回答

9

這兩個時間點在不同的時區。所以這個差別其實是正確的。你可以看到,隨着

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

所以基本上$then是UTC時間,而$now在任何時區環境認爲它是。 爲了解決這個問題,你需要在你想要什麼時區決定。

+0

優秀的,就是這樣。謝謝 – user1768233

2

正如DeVadder已經說過的,這是因爲Time::Piece默認爲UTC的分析時間。

假設你想用你的localtime,你其實可以鼓勵解析次繼承本地時區的,像這樣完成這一切:

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"; 

輸出:

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 
相關問題