如果我有位置,我知道如何使用时区转换获取当地时间:
my $localTime = DateTime->now( time_zone => 'America/New_York' );
但我目前只有UTC TimeZone号码,例如:
my $UTCzone = 5;
my $UTCzone = -2;
etc.
在这种情况下如何转换?
答案 0 :(得分:5)
DateTime->now( time_zone => '+0500' );
perldoc DateTime
说
time_zone参数可以是标量或DateTime :: TimeZone对象。字符串将简单地作为其“name”参数传递给DateTime :: TimeZone-> new方法。此字符串可能是Olson DB时区名称(“America / Chicago”),偏移字符串(“+ 0630”),
答案 1 :(得分:2)
DateTime接受时区的偏移量。例如,纽约目前位于UTC-0400
,因此您可以使用
DateTime->now( time_zone => '-0400' ); # Or -0330, +0100, etc
但请注意,这与提供America/New_York
的时区不同,因为纽约的DST每年两次更改偏差。
$ 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