上次做項目時,發現一個問題,這裏記錄一下:
問題:
在使用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')));