猿问

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-d\n");

    $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 日。这是为什么?


炎炎设计
浏览 125回答 1
1回答

慕的地8271018

这是由于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:522020-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非零时间,where$month_end有一个零时间,因此<=比较失败。您可以通过向第一个值添加时间部分以强制其为 0 来解决此问题:$month_start = new DateTime("first day of this month 00:00");然后您的循环将按预期工作:Demo on 3v4l.org。
随时随地看视频慕课网APP
我要回答