应使用 date('Y-m-t', strtotime('first day of this month -1 day')) 或 DateTime 类:$d = new DateTime('first day of this month'); $d->modify('-1 day'); echo $d->format('Y-m-d');,避免 strtotime('last month') 在1月或月末导致的逻辑错误。

PHP用 date() 和 strtotime() 获取上个月最后一天容易出错
直接写 date('Y-m-t', strtotime('last month')) 看似简洁,但一到 1 月或月末(如 31 号)就会翻车。比如 2024-01-01 执行时,strtotime('last month') 返回的是 2023-12-01(不是 2023-11-30),再套 t 就得 2023-12-31 —— 表面正确,实则逻辑脆弱:它依赖“当前日期在当月第几天”来推算“last month”,而用户真正要的只是“上个月的最后一天”,和今天几号无关。
推荐做法是锚定本月第一天,倒推一天:
-
date('Y-m-t', strtotime('first day of last month'))不可靠,仍受当前日影响 - 正确姿势:
date('Y-m-t', strtotime('first day of this month -1 day')) - 更清晰写法(推荐):
date('Y-m-t', strtotime('this month -1 second'))—— 利用时间戳截断特性,避免日期进位问题
用 DateTime 类处理边界更安全,尤其跨年、闰年
面向对象方式天然规避字符串解析歧义,DateTime 的 modify() 和 format() 组合更可控:
php
$date = new DateTime('first day of this month');
$date->modify('-1 day');
echo $date->format('Y-m-d'); // 如 2024-02-29(2024 是闰年)
关键点:
立即学习“PHP免费学习笔记(深入)”;
- 不要用
new DateTime('last month')—— 它等价于strtotime('last month'),同样有 1 月陷阱 - 必须以
first day of this month为起点,再减 1 天,才能稳定落到上月月末 -
DateTime::createFromFormat()在解析用户输入日期时才需要,此处无需
注意 t 格式符的隐含行为:它返回当月天数,不是“上月天数”
很多人误以为 date('t', $timestamp) 能自动返回“$timestamp 所在月份的最后一天”,其实它只返回该月总天数(如 31),不拼日期。所以 date('Y-m-', $ts) . date('t', $ts) 是错的 —— 若 $ts 是 2024-02-01,则 date('t', $ts) 返回 29,结果变成 2024-02-29,而非上月(1 月)的 31。
正确组合只有两种:
- 用
date('Y-m-t', $ts),但 $ts 必须是上个月某一天的时间戳(如上例中用first day of this month -1 day得到的) - 或用
date('Y-m-t', strtotime('last day of last month'))—— 这个字符串虽冗长,但语义明确且 PHP 8.0+ 支持稳定
生产环境建议封装成函数并加类型提示
实际项目里别重复写逻辑,尤其涉及 cron 或报表定时任务时,日期偏差会导致数据漏算。一个带注释的最小可用函数:
php
function get_last_day_of_last_month(): string
{
$date = new DateTime('first day of this month');
$date->modify('-1 day');
return $date->format('Y-m-d');
}
// 调用:get_last_day_of_last_month() → '2024-02-29'
注意事项:
- 不要加
date_default_timezone_set()在函数里 —— 时区应由框架或入口统一设置 - 如果系统需支持毫秒级精度(极少见),
DateTimeImmutable更合适,避免意外修改原对象 - 传入参数?没必要。这个需求本质是“相对当前时间”的计算,硬加参数反而增加调用方理解成本
最易被忽略的一点:所有基于 strtotime() 的写法,在 PHP 8.2+ 已标记为 legacy,虽然暂未废弃,但 DateTime 是唯一长期受支持路径。



















