为什么在8:30将6天半小时加到午夜?

时间:2013-03-05 08:05:00

标签: perl datetime

此示例采用基准日期并增加7½小时,1天7½小时,2天7½小时等等。

use Date::Manip;
use DateTime;
use DateTime::Format::DateManip;

Date::Manip::Date_Init("TZ=America/New_York", "Language=English");

my $otime = DateTime->new(
    year      => 2013,
    month     => 3,
    day       => 4,
    hour      => 0,
    minute    => 0,
    second    => 0,
    time_zone => 'America/New_York',
);

my $t1 = UnixDate($otime, "%i:%M %p on %A, %B %e, %Y ");
print "original $t1\n";

for (my $i = 0; $i <= 20; $i++) {               
    my $dtw = $otime->clone();
    $dtw->add(
        minutes => (15) * 30,
        days    => ($i),
    ); 
    $t1 = UnixDate($dtw, "%i:%M %p on %A, %B %e, %Y ");
    print "$i days $t1\n";
}

当添加6天7个半小时时,结果包含额外的一小时。

original 12:00 AM on Monday, March 04, 2013
0 days 07:30 AM on Monday, March 04, 2013
1 days 07:30 AM on Tuesday, March 05, 2013
2 days 07:30 AM on Wednesday, March 06, 2013
3 days 07:30 AM on Thursday, March 07, 2013
4 days 07:30 AM on Friday, March 08, 2013
5 days 07:30 AM on Saturday, March 09, 2013
6 days 08:30 AM on Sunday, March 10, 2013    # why 8:30 and not 7:30?
7 days 07:30 AM on Monday, March 11, 2013
8 days 07:30 AM on Tuesday, March 12, 2013
9 days 07:30 AM on Wednesday, March 13, 2013
10 days 07:30 AM on Thursday, March 14, 2013
11 days 07:30 AM on Friday, March 15, 2013
12 days 07:30 AM on Saturday, March 16, 2013
13 days 07:30 AM on Sunday, March 17, 2013
14 days 07:30 AM on Monday, March 18, 2013
15 days 07:30 AM on Tuesday, March 19, 2013
16 days 07:30 AM on Wednesday, March 20, 2013
17 days 07:30 AM on Thursday, March 21, 2013
18 days 07:30 AM on Friday, March 22, 2013
19 days 07:30 AM on Saturday, March 23, 2013
20 days 07:30 AM on Sunday, March 24, 2013

1 个答案:

答案 0 :(得分:19)

因为夏令时开始于2013年3月10日在America / New_York时区。 DateTime首先添加$i天(3月10日午夜),然后加上450分钟到达上午8:30(因为3月10日凌晨1点59分之前的分钟是凌晨3点) 。 add参数的顺序没有意义;见Adding a Duration to a Datetime

因为它增加了几天和几天。分开处理(并处理第一天),效果仅发生在DST实际开始或结束的日期。如果您想要特定时间,请直接set直接而不是使用add。或者拨打add两次,一次添加分钟,然后再添加几天。