zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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日,再根据自己的需求处理即可!