2011-09-07 228 views
0

我需要找出什麼是當地時間在給定的位置。我有該地點的GMT/UTC抵消。我試圖通過在該時區中設置截止日期之間的差異來獲得持續時間,以便在特定時區內滿足截止日期時觸發電子郵件。如何計算在GMT時區給定的GMT/UTC偏移量在本地時間?

例如:如果西雅圖截止日期爲2011年9月10日12:00:00格林威治標準時間-7:00現在如果我在英國我需要計算現在在西雅圖現在什麼時間格林威治時間抵消-7: 00一旦我得到,我可以計算差異,如果差異是0,那麼我會發出一封電子郵件說,截止日期是滿足。

如何在Perl中做時間計算部分?

請幫忙。

感謝, Sunyl

回答

3

創建一個DateTime對象,並將其與DateTime->now。 DateTime對象知道與其中的時間戳相關聯的時區,所以它可以做你想做的事,不用大驚小怪。

use strict; 
use warnings; 
use feature qw(say); 

use DateTime qw(); 
use DateTime::Format::Strptime qw(); 

my $strp = DateTime::Format::Strptime->new(
    pattern => '%b %d, %Y %H:%M:%S GMT%z', 
    locale => 'en', 
    on_error => 'croak', 
); 

my $target = 'Sep 10, 2011 12:00:00 GMT-0700'; 

my $target_dt = $strp->parse_datetime($target); 
my $now_dt = DateTime->now(); 

if ($now_dt > $target_dt) { 
    say "It's too late"; 
} else { 
    say "It's not too late"; 
} 

$target_dt->set_time_zone('local'); 
say "The deadline is $target_dt, local time"; 

上面我假設你錯誤地使用了日期格式。如果日期按照您提供的格式設置,則您將無法使用Strptime,因爲時間戳使用非標準名稱來表示月份,偏移量使用非標準格式。

my @months = qw(... Sept ...); 
my %months = map { $months[$_] => $_+1 } 0..$#months; 

my ($m,$d,$Y,$H,$M,$S,$offS,$offH,$offM) = $target =~ 
     /^(\w+) (\d+), (\d+) (\d+):(\d+):(\d+) GMT ([+-])(\d+):(\d+)\z/ 
    or die; 

my $target_dt = DateTime->new(
    year  => $Y, 
    month  => $months{$m}, 
    day  => 0+$d, 
    hour  => 0+$H, 
    minute => 0+$M, 
    second => 0+$S, 
    time_zone => sprintf("%s%04d", $offS, $offH * 100 + $offM), 
); 
+0

感謝這幫助了很多...我想我得到了我一直在尋找... – Sunyl

+0

@Sunyl,我追加兩行第一個片段。我應該幫助澄清你的疑問。 – ikegami

3

您可以使用datetime模塊從CPAN做的時間計算。

http://metacpan.org/pod/DateTime

它有時間帶的東西,你可以利用爲好。應該非常簡單,因爲文檔非常清晰。

具體來說,

$dt->subtract_datetime($datetime) 

This method returns a new DateTime::Duration object representing the difference between the two dates. The duration is relative to the object from which $datetime is subtracted. For example: 

    2003-03-15 00:00:00.00000000 
- 2003-02-15 00:00:00.00000000 
------------------------------- 
= 1 month 

Note that this duration is not an absolute measure of the amount of time between the two datetimes, because the length of a month varies, as well as due to the presence of leap seconds. 

希望幫助!

編輯:

而且這可能是重要的/將使生活更輕鬆,

use UTC for all calculations 

If you do care about time zones (particularly DST) or leap seconds, try to use non-UTC time zones for presentation and user input only. Convert to UTC immediately and convert back to the local time zone for presentation: 

my $dt = DateTime->new(%user_input, time_zone => $user_tz); 
$dt->set_time_zone('UTC'); 

# do various operations - store it, retrieve it, add, subtract, etc. 

$dt->set_time_zone($user_tz); 
print $dt->datetime; 
相關問題