php 使用strtotime('-1 month')获取上一个月月份的Bug

以Y-m-d格式输出上一个月的日期:date('Y-m-d',strtotime("-1 month"));  ==》输出结果2018-02-28(当前时间为2018-03-28)
 
不过strtotime("-1 month") 在此处会有bug,当上一个月或者下一个月没有今天的日时,会输出错误,比如今天是3月30号,但是2月份没有30号,此时date('Y-m-d',strtotime("-1 month")); 输出的结果就是 2018-03-01
 
同理,当在3月31号/5月31号/7月31号/10月31号/12月31号执行date('Y-m-d',strtotime("-1 month"))时,得到的结果是 3月1号/5月1号//7月1号/10月1号/12月1号。

终极解法是:

要先获取上个月第一日,在做其他处理。

代码如下:

$month_first = date('Y-m-01', strtotime(date('Y-m-01') . " - 1 month"));//上个月第一天
$last_month_first = date('Y-m-t', strtotime(date('Y-m-01') . " - 1 month"));//上个月最后一天`
发布了12 篇原创文章 · 获赞 5 · 访问量 6238

猜你喜欢

转载自blog.csdn.net/baidu13686718253/article/details/103788078