php中关于strtotime函数31日取前几个月日期的BUG
2023-03-07 09:51:53 时间
在使用php脚本中的 strtotime 函数取前几个月的日期时,发现每到31日时,取出的前几个月的日期都会出现错误。仔细检查了一下,发现在利用 strtotime 函数取前几个月的日期时,给 strtotime 函数的参数并不规范,strtotime 函数的时间划算会出现问题。
strtotime函数取前几月日期的错误复现
示例代码:
复制
# ymkuz.com
// $now = date('Y-m-d');
$now = '2022-08-31'; //为了复现BUG,这里的日期设置为一个有31号的月份
$time = strtotime($now.' -1 month');
echo date('Y-m-d',$time); // 2022-07-31
echo '<hr>';
$time2 = strtotime(date('Y-m-01', strtotime($now.' -2 month')));
echo date('Y-m-d',$time2); // 2022-07-01
echo '<hr>';
$time3 = strtotime(date('Y-m-01', strtotime($now.' -3 month')));
echo date('Y-m-d',$time3); // 2022-05-01
echo '<hr>';
$time4 = strtotime(date('Y-m-01', strtotime($now.' -4 month')));
echo date('Y-m-d',$time4); // 2022-05-01
echo '<hr>';
$time5 = strtotime(date('Y-m-01', strtotime($now.' -5 month')));
echo date('Y-m-d',$time5); // 2022-03-01
echo '<hr>';
$time6 = strtotime(date('Y-m-01', strtotime($now.' -6 month')));
echo date('Y-m-d',$time6); // 2022-03-01
PS:
1、通过上面的代码可以看到,利用 strtotime() 函数取上个月,上上个月的日期是从一个指定日期(也可以是当前的日期)进行月份的相减,从而获得想要的日期。
2、如果 strtotime() 函数指定的日期为31号,那么从其基础上减去月份的日期里面如果没有31日,那么 strtotime() 函数就会取一个相近的日期进行输出,这就造成了每到31日时取日期错误的BUG。
strtotime函数取前几月日期正确的方法
示例代码:
复制
# ymkuz.com
// $now = date('Y-m-01'); //当前月份的开始时间
$now = '2022-08-01'; //调整被减去时间为每月的1号即可。
$time = strtotime($now.' -1 month');
echo date('Y-m-d',$time); // 2022-07-31
echo '<hr>';
$time2 = strtotime(date('Y-m-01', strtotime($now.' -2 month')));
echo date('Y-m-d',$time2); // 2022-06-01
echo '<hr>';
$time3 = strtotime(date('Y-m-01', strtotime($now.' -3 month')));
echo date('Y-m-d',$time3); // 2022-05-01
echo '<hr>';
$time4 = strtotime(date('Y-m-01', strtotime($now.' -4 month')));
echo date('Y-m-d',$time4); // 2022-04-01
echo '<hr>';
$time5 = strtotime(date('Y-m-01', strtotime($now.' -5 month')));
echo date('Y-m-d',$time5); // 2022-03-01
echo '<hr>';
$time6 = strtotime(date('Y-m-01', strtotime($now.' -6 month')));
echo date('Y-m-d',$time6); // 2022-02-01
修复方法:只需要将 strtotime 处理日期的基础日期调整为指定月份的1日即可,然后获取的日期都是指定月期的1日,再根据自己的需求处理即可!
相关文章
- YApi 使用Firefox插件cross-request关于cookie的问题
- 解密Prompt系列1. Tunning-Free Prompt:GPT2 & GPT3 & LAMA & AutoPrompt
- CrossOver2023Mac电脑上运行切换Win软件工具
- Polarr Photo Editor2023最新版修图工具功能介绍
- 经济学:动态模型平均(DMA)、动态模型选择(DMS)、ARIMA、TVP预测原油时间序列价格|附代码数据
- 基于R语言混合效应模型(mixed model)案例研究|附代码数据
- 工地安全帽智能识别系统
- ImageRanger Pro Edition for Mac(图片管理器)
- 三星:成熟制程减产传闻不实,会设法满足客户需求
- 鸿海拟在印度培训人才,以满足当地半导体产业需求
- 中科二期扩建环评过关,台积电2nm厂即将启动
- 成本大幅上涨,英特尔要求将德国建厂补贴增加至100亿欧元
- Bing+Edge+ChatGPT,微软誓要重塑搜索
- 传三星、SK海力士高层紧急赴美,争取“芯片法案”及对华新规豁免权
- 新思科技DSO.ai助力客户完成100次流片,引领AI在芯片设计中的规模化应用
- 订单锐减!安靠上海厂超4000员工放假一周!
- 中芯国际去年营收突破495亿元!中芯深圳投产,中芯京城试产!
- 中国激光雷达第一股!禾赛科技成功登陆纳斯达克:市值超26亿美元!
- Q4净利大跌49%!日月光投控拟将25%的SiP封装产能转移出大陆!
- 程序员接外包注意事项