2012-12-27 56 views
1

我正在使用DateTime模塊。但是它提供了錯誤的時間。請考慮下面的代碼:perl「DateTime」模塊打印錯誤時間

#!/usr/bin/perl -w 
use strict; 

use Time::localtime; 
my $now = ctime(); 
print $now."\n"; 

print "------------------------------\n"; 

use DateTime; 
my $dt = DateTime->now; 
print $dt."\n"; 

,其輸出是:

Wed Dec 26 22:11:52 2012 
------------------------------ 
2012-12-27T06:11:52 

所以,你可以看到,DateTime輸出8小時,這是錯誤的領導。這裏是Linux date命令的輸出:

# date 
Wed Dec 26 22:13:17 PST 2012 

因此,date命令的輸出與time::localtime輸出相匹配。

你能幫我理解我在使用DateTime模塊時出錯的地方嗎?

- 謝謝。

UPDATE:

從興田CPAN文檔:

DateTime->now(...) 

This class method is equivalent to calling from_epoch() with the value returned from Perl's time() function. Just as with the new() method, it accepts "time_zone" and "locale" parameters. 

By default, the returned object will be in the UTC time zone. 

所以,看來返回的時間爲UTC。但是,我在PST的時區。可能這就是爲什麼我看到不同的時間。

+0

我假設你是在太平洋時區?你需要告訴DateTime你想要什麼時區。 –

+1

是的,我剛剛更新了我的帖子。它返回UTC時間。進一步閱讀以瞭解如何傳遞時區信息。謝謝。 – slayedbylucifer

+1

你剛剛用時區學到了第一課。從今以後,當時間不符合你的預期時,你會首先考慮的是檢查時區。 –

回答

8

我順利通過了區信息,現在完美的作品:

#!/usr/bin/perl -w 
use strict; 

use Time::localtime; 
my $now = ctime(); 
print $now."\n"; 

print "------------------------------\n"; 

use DateTime; 
my $dt = DateTime->now (time_zone => 'America/Los_Angeles'); 
print $dt."\n"; 

輸出:

Wed Dec 26 22:28:44 2012 
------------------------------ 
2012-12-26T22:28:44 

爲東海岸

my $dateF = DateTime->now(time_zone => 'America/New_York')->ymd; 
+4

優秀。你現在可以接受你自己的答案。 –

+2

真棒..我不知道! – slayedbylucifer

+0

是的,你可以接受! :)幾個小時後,但! –