gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:32:59 25 4
gpt4 key购买 nike

我正在尝试使用 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

关于Perl DateTime "is_dst()"方法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40140443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com