PHP中使用date獲取上月最後一天出現的問題

上次做項目時,發現一個問題,這裏記錄一下:

問題:

在使用date函數獲取上一個月最後一天或下個月最後一天時,如果當前日期是31號,獲取的數據有問題。

// 2019-12-01   正確應該是 2019-11-30
date('Y-m-d', strtotime('+1 month', strtotime('2019-10-31')));
// 2019-10-01   正確應該是 2019-09-30
date('Y-m-d', strtotime('-1 month', strtotime('2019-10-31')));

解決辦法:

可以使用“last day of”來獲取最後一天。

// 2019-11-30
date('Y-m-d', strtotime('last day of +1 month', strtotime('2019-10-31')));
// 2019-09-30
date('Y-m-d', strtotime('last day of -1 month', strtotime('2019-10-31')));

測試後發現獲取第一天數據也有同樣的問題:
相應的可以使用“first day of”來獲取第一天數據。

// 2019-11-01
date('Y-m-d', strtotime('first day of +1 month', strtotime('2019-10-31')));
// 2019-09-01
date('Y-m-d', strtotime('first day of -1 month', strtotime('2019-10-31')));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章