You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:04:56