按照通用编程的思想,函数之外的变量应该被视为全局变量。如果是全局变量,在函数中调用没有问题。本文主要和大家分享php调用函数之外的变量方法,希望对你有所帮助。php和我们的传统思维好像有点问题,那么
顺晟科技
2022-09-15 09:16:38
56
在使用php脚本中的 strtotime 函数取前几个月的日期时,发现每到31日时,取出的前几个月的日期都会出现错误。仔细检查了一下,发现在利用 strtotime 函数取前几个月的日期时,给 strtotime 函数的参数并不规范,strtotime 函数的时间划算会出现问题。
strtotime函数取前几月日期的错误复现示例代码:
# 顺晟科技博客 feiniaomy.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函数取前几月日期正确的方法示例代码:
# 顺晟科技博客 feiniaomy.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日,再根据自己的需求处理即可!
30
2022-11
30
2022-11
30
2022-11
30
2022-11
28
2022-11
21
2022-10