如何在Perl中计算给定GMT/UTC偏移的时区的本地时间



我需要找出给定位置的当地时间。我有那个位置的GMT/UTC偏移量。我正试图通过在该时区设置的截止日期之间的差异来获得一个时间持续时间,以触发在该特定时区的截止日期满足时发送的电子邮件。

交货。如果西雅图的截止日期设置为2011年9月10日12:00:00 GMT -现在7:00如果我在英国,我需要计算现在西雅图的时间给定GMT偏移量-7:00一旦我得到,我可以计算差值,如果差值为0,然后我将发送一封电子邮件说截止日期已经满足。

如何在Perl中做时间计算部分?

请帮助。

谢谢,Sunyl

创建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),
);
  • DateTime
  • DateTime::格式::Strptime

可以使用CPAN中的DateTime模块进行时间计算。

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;

相关内容

  • 没有找到相关文章

最新更新