亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP 日期未正確迭代

PHP 日期未正確迭代

PHP
炎炎設計 2022-11-12 10:00:58
我試圖迭代從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-012020-03-022020-03-03...2020-04-272020-04-282020-04-29如您所見,盡管<=在比較中使用了 ,但輸出中缺少 4 月 30 日。這是為什么?
查看完整描述

1 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

這是由于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非零時間,where$month_end有一個零時間,因此<=比較失敗。


您可以通過向第一個值添加時間部分以強制其為 0 來解決此問題:


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

然后您的循環將按預期工作:Demo on 3v4l.org。



查看完整回答
反對 回復 2022-11-12
  • 1 回答
  • 0 關注
  • 114 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號