【原创】PHP上月时间计算的bug

【原创】PHP上月时间计算的bug

date(‘Y-m-d H:i:s’, strtotime(‘-1 month’));

计算步骤:
期望结果:2026 年 2 月 31 日
问题:2026 年2 月只有 28 天,没有 31 日
PHP 的处理:从 2 月 1 日开始往后数 31 天
2 月有 28 天
31 – 28 = 3 天溢出
所以进位到 3 月 3 日

这种方式计算上一个月的时间有问题哈,可以使用下面的方式替换

$firstDay = date(‘Y-m-d H:i:s’, strtotime(‘first day of last month’));
$lastDay = date(‘Y-m-d H:i:s’, strtotime(‘last day of last month’));

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据