php strtotime日期处理存在一个问题,就是在每月31日或者在当月天数小于30天时,加减一个月得到的月份是不对的。
例如:
echo date('Y-m-d',strtotime("2022-10-31 +1 month"));//得到 2022-12-01
echo date('Y-m-d',strtotime("2022-10-31 -1 month"));//得到 2022-10-01
echo date('Y-m-d',strtotime("2023-01-31 +1 month"));//得到2023-03-03
echo date('Y-m-d',strtotime("2023-03-31 -1 month"));//得到2023-02-03
也就是在使用strtotime进行加减月计算时,如果天数小于30天或者大于30天就会出现跳月问题。
解决这一类的问题可以使用PHP date新增的一系列修正短语, first day of 和 last day of,来解决这样的问题。
echo date("Y-m-d", strtotime("last day of +1 month", strtotime('2023-01-31')));//得到2023-02-28
echo date("Y-m-d", strtotime("last day of -1 month", strtotime('2023-03-31')));//得到2023-02-28
echo date("Y-m-d", strtotime("first day of +1 month", strtotime('2023-01-31')));//得到2023-02-01
echo date("Y-m-d", strtotime("first day of -1 month", strtotime('2023-03-31')));//得到2023-02-01
这样就能解决strtotime进行加减月计算时的跳月问题
最后
以上就是文静彩虹最近收集整理的关于php strtotime 每月31日 加/减一个月的问题的全部内容,更多相关php内容请搜索靠谱客的其他文章。
发表评论 取消回复