Perl DateTime "is_dst()" 方法无法正常工作

Perl DateTime "is_dst()" method not working correctly

我正在尝试使用 DateTime 模块中的 is_dst() 方法来确定是否正在进行夏令时转换。

我首先写了一个非常基本的例子,我 确定 可以工作,但由于某种原因,我得到了意想不到的结果。


示例:

#!/usr/bin/perl

use strict;
use warnings;
use DateTime;

my $dt1 = DateTime->new(
    'year'  => 2015,
    'month' => 3   ,
    'day'   => 8   ,
    'hour'  => 3   ,
);

my $dt2 = DateTime->new(
    'year'  => 2015,
    'month' => 3   ,
    'day'   => 7   ,
    'hour'  => 3   ,
);

print $dt1."\n";
print $dt2."\n";
print $dt1->is_dst()."\n";
print $dt2->is_dst()."\n";

I started with a date that I knew was a daylight savings transition: Sunday, March 8, 2015. I chose 3 AM because I knew that the daylight savings transition would have already occured at that point in time.

Then I took a date that I knew was before the daylight savings transition: Saturday, March 7, 2015 also at 3 AM.

Then I print the two dates and their corresponding DST flags.

输出:

2015-03-08T03:00:00
2015-03-07T03:00:00
0
0

这两个日期的打印完全符合预期,但出于某种原因,即使第一个日期出现在夏令时期间,而第二个日期出现在夏令时之前,但并未为这两个日期设置 DST 标志。

为什么这不能正常工作?我错过了什么吗?

你必须explicitly set the time zone:

The default time zone for new DateTime objects, except where stated otherwise, is the "floating" time zone...A floating datetime is one which is not anchored to any particular time zone.

例如:

use strict;
use warnings;
use DateTime;

my $dt1 = DateTime->new(
    'year'      => 2015,
    'month'     => 3,
    'day'       => 8,
    'hour'      => 3,
    'time_zone' => 'America/New_York'
);

my $dt2 = DateTime->new(
    'year'      => 2015,
    'month'     => 3,
    'day'       => 7,
    'hour'      => 3,
    'time_zone' => 'America/New_York'
);

print $dt1."\n";
print $dt2."\n";
print $dt1->is_dst()."\n";
print $dt2->is_dst()."\n";

输出:

2015-03-08T03:00:00
2015-03-07T03:00:00
1
0