PHP日期迭代不正确



我试图将日期从first day of this month迭代到last day of April:

$month_start = new DateTime("first day of this month");
$month_end = new DateTime("last day of April");
while ($month_start <= $month_end) {
echo $month_start->format("Y-m-dn");
$month_start->add(new DateInterval('P1D'));
}

截至2020年3月22日的产量(演示(:

2020-03-01
2020-03-02
2020-03-03
...
2020-04-27
2020-04-28
2020-04-29

正如您所看到的,尽管在比较中使用了<=,但输出中缺少4月30日。为什么?

这是由于DateTime构造函数处理first day of相对时间的方式不一致:

$month_start = new DateTime("first day of this month");
echo $month_start->format('Y-m-d H:i:s') . "n";
$month_start = new DateTime("first day of March");
echo $month_start->format('Y-m-d H:i:s') . "n";

截至2020年3月22日的产量(演示(:

2020-03-01 03:49:52
2020-03-01 00:00:00

请注意,first day of this month变量具有非零时间部分。然而,当你计算$month_end值时,你会得到一个零时间:

$month_end = new DateTime("last day of April");
echo $month_end->format('Y-m-d H:i:s') . "n";

输出(演示(:

2020-04-30 00:00:00

因此,代码中的循环失败,因为$month_start以非零时间到达2020-04-30,其中$month_end的时间为零,因此<=比较失败。

你可以通过在第一个值上添加一个时间部分来强制它为0:来解决这个问题

$month_start = new DateTime("first day of this month 00:00");

然后你的循环将按预期工作:在3v4l.org.上演示

最新更新