如何使用UTC偏移量获取Perl中的本地时间



如果我有位置,我知道如何使用时区转换获得本地时间:

my $localTime = DateTime->now( time_zone => 'America/New_York' );

但我目前只有UTC时区编号,例如:

my $UTCzone = 5;
my $UTCzone = -2;
etc.

在这种情况下,我该如何转换?

DateTime->now( time_zone => '+0500' );

perldoc DateTime表示

time_zone参数可以是标量或DateTime::TimeZone对象。一个字符串将作为其"name"参数简单地传递给DateTime::TimeZone->new方法。该字符串可能是Olson DB时区名称("America/Chiccago")、偏移字符串("+0630")、

DateTime接受时区的偏移量。例如,纽约目前处于UTC-0400,因此您可以使用
DateTime->now( time_zone => '-0400' );  # Or -0330, +0100, etc

但请注意,这与提供America/New_York时区不同,因为纽约夏令时的偏移量每年变化两次。

$ perl -MDateTime -E'
   for my $time_zone (qw(America/New_York -0400)) {
      my $dt = DateTime->now( time_zone => $time_zone );
      say "Timezone       = $time_zone";
      say "Now            = ", $dt->strftime("%T");
      say "UTC            = ", $dt->clone->set_time_zone("UTC")->strftime("%T");
      $dt->add( months => 6 );
      say "+6 months      = ", $dt->strftime("%T");
      say "+6 months, UTC = ", $dt->clone->set_time_zone("UTC")->strftime("%T");
      say "";
   }
'
Timezone       = America/New_York
Now            = 19:36:33
UTC            = 23:36:33
+6 months      = 19:36:33
+6 months, UTC = 00:36:33
Timezone       = -0400
Now            = 19:36:33
UTC            = 23:36:33
+6 months      = 19:36:33
+6 months, UTC = 23:36:33

相关内容

  • 没有找到相关文章

最新更新