PHP日期疑问:3月30日减1个月为何得3月1日而非2月29日?
PHP日期modify('-1 month')输出异常原因解析
先修正你给出的代码(原代码缺少DateTime实例化步骤):
$today_date_md = new DateTime("2020-03-30"); $dt_upto_pre_ = $today_date_md->modify('-1 month'); echo $dt_upto_pre_->format('Y-m-d'); // 实际输出2020-03-01
问题原因
PHP的DateTime::modify()处理相对月份调整时,遵循先增减月份,再修正无效日期的逻辑:
- 第一步:将2020-03-30的月份减1,得到理论日期
2020-02-30。 - 第二步:2020年是闰年,2月最多只有29天,
2020-02-30属于无效日期。PHP会自动将这个无效日期向后推算,从2月29日再加1天,最终得到2020-03-01。
正确实现方式
如果要获取上月最后一天,直接使用last day of -1 month的相对时间格式即可:
$today_date_md = new DateTime("2020-03-30"); $dt_upto_pre_ = $today_date_md->modify('last day of -1 month'); echo $dt_upto_pre_->format('Y-m-d'); // 输出2020-02-29
也可以先定位到当月第一天,再往前推一天得到上月最后一天:
$today_date_md = new DateTime("2020-03-30"); $today_date_md->modify('first day of this month')->modify('-1 day'); echo $today_date_md->format('Y-m-d'); // 输出2020-02-29
内容的提问来源于stack exchange,提问作者Bacha
相关产品推荐
相关产品推荐

