最近使用了strtotime结合-1 month, +1 month, next month获取上个月或者下个月的日期,不过刚看到一篇文章,才知道原来使用strtotime直接获取日期还是有点小BUG
BUG
如日期:
1 2 | $today = '2020-12-31' ; echo date ( "Y-m-d" , strtotime ( "$today -1 month" )) |
输出
1 | 2020-12-01 |
根据上面的输出可以看出来,输出的还是2020年12月
分析:
先做-1 month, 那么当前是07-31, 减去一以后就是06-31.
再做日期规范化, 因为6月没有31号, 所以就好像2点60等于3点一样, 6月31就等于了7月1
是不是逻辑很”清晰”呢? 我们也可以手动验证第二个步骤, 比如:
1 2 | var_dump( date ( "Y-m-d" , strtotime ( "2020-12-31" ))); // 输出2020-12-01 |
也就是说, 只要涉及到大小月的最后一天, 都可能会有这个迷惑, 我们也可以很轻松的验证类似的其他月份, 印证这个结论:
1 2 3 4 5 6 7 8 9 10 11 | var_dump( date ( "Y-m-d" , strtotime ( "-1 month" , strtotime ( "2020-12-31" )))); // 输出2020-12-03 var_dump( date ( "Y-m-d" , strtotime ( "+1 month" , strtotime ( "2020-08-31" )))); // 输出2020-10-01 var_dump( date ( "Y-m-d" , strtotime ( "next month" , strtotime ( "2020-01-31" )))); // 输出2020-03-03 var_dump( date ( "Y-m-d" , strtotime ( "last month" , strtotime ( "2020-03-31" )))); // 输出2020-03-03 |
解决方案
从PHP5.3开始呢, date新增了一系列修正短语, 来明确这个问题, 那就是”first day of” 和 “last day of”, 也就是你可以限定好不要让date自动”规范化”:
1 2 3 4 5 6 7 8 9 10 11 | var_dump( date ( "Y-m-d" , strtotime ( "last day of -1 month" , strtotime ( "2020-03-31" )))); //输出2020-02-28 var_dump( date ( "Y-m-d" , strtotime ( "first day of +1 month" , strtotime ( "2020-08-31" )))); //输出2020-09-01 var_dump( date ( "Y-m-d" , strtotime ( "first day of next month" , strtotime ( "2020-01-31" )))); //输出2020-02-01 var_dump( date ( "Y-m-d" , strtotime ( "last day of last month" , strtotime ( "2020-03-31" )))); //输出2020-02-28 |
那如果是5.3之前的版本, 可以使用mktime之类的, 把所有的日子忽略掉, 比如都限定为每月1号就可以了, 只不过就不如直接用first day来的更加优雅.
上一篇:
PHP获取数组中含有相同元素的方法
下一篇:
PHP死循环写法和作用
友情提示:垃圾评论一律封号...