PHP strtotime在闰年期间少了一天。

问题描述 投票:0回答:2

我试图通过使用strtotime在第一个日期上添加13天来生成一个连续日期周期的列表,就像这样。

$start = strtotime(date('2020-06-01'));

for($x = 1; $x<=10; $x++) // increment $x until 10
{
    $period     = $start - ($x * 1209600); // 1209600 is equivalent to 14 days. Multiply by $x
    $period_end = date('Y-m-d', strtotime(date('Y-m-d', $period). ' + 13 days'));
    echo date('Y-m-d', $period) . " - " . $period_end ."<br>";
}

输出结果是这样的

2020-05-18 - 20-05-31
2020-05-04 - 20-05-17
2020-04-20 - 20-05-03
2020-04-06 - 20-04-19
2020-03-23 - 20-04-05
2020-03-09 - 20-03-22
2020-02-23 - 20-03-07
2020-02-09 - 20-02-22
2020-01-26 - 20-02-08
2020-01-12 - 20-01-25

一切都和预期的一样,直到它进入 "2020 -02 -23 -20 -03 -07 "范围。 它应该报告'2020-02-24 - 2020-03-08'为什么会偏移1天? 这是不是PHP strtotime中的一个与闰年有关的错误?

编辑:这不是一个闰年的问题。 原来是我所在时区的夏令时问题。 当DST发生在38日时,从纪元开始的秒数时间改变了一个小时。这使我的日期提前了1个小时,最后变成了前一天。

php date strtotime leap-year
2个回答
1
投票

如果我们添加 H:i 到你的date(),这一切都变得清晰起来。

$start = strtotime(date('2020-06-01'));

for($x = 1; $x<=10; $x++) // increment $x until 10
{
    $period     = $start - ($x * 1209600); // 1209600 is equivalent to 14 days. Multiply by $x
    $period_end = date('Y-m-d H:i', strtotime(date('Y-m-d H:i', $period). ' + 13 days'));
    echo date('Y-m-d H:i', $period) . " - " . $period_end ."<br>\n";
}

输出。

2020-05-18 00:00 - 2020-05-31 00:00<br>
2020-05-04 00:00 - 2020-05-17 00:00<br>
2020-04-20 00:00 - 2020-05-03 00:00<br>
2020-04-06 00:00 - 2020-04-19 00:00<br>
2020-03-22 23:00 - 2020-04-04 23:00<br>
2020-03-08 23:00 - 2020-03-21 23:00<br>
2020-02-23 23:00 - 2020-03-07 23:00<br>
2020-02-09 23:00 - 2020-02-22 23:00<br>
2020-01-26 23:00 - 2020-02-08 23:00<br>
2020-01-12 23:00 - 2020-01-25 23:00<br>

r3mainer注释是正确的。添加 12:00 到开始,问题就会消失。因为你去掉一个小时的日光节约太多,就不是闰年了。

$start = strtotime(date('2020-06-01 12:00'));

https:/3v4l.orgUj2CA

© www.soinside.com 2019 - 2024. All rights reserved.