1.最近做数据可视化 用的图表 echarts.js
然后传参横坐标日期时用到了strtotime这个函数,结果发现有坑,昨天是2019-05-30都是正常的,发版后今天31号就全错了
原代码
function createMonthLine($monthLong, $format= "ym"){
$monthLine = [];
for ($i=1; $i<= $monthLong; $i++){
$monthLine[] = date($format, strtotime("-".($monthLong-$i)." month"));
}
return $monthLine;
}
新代码
function createMonthLine($monthLong, $format= "ym"){
$monthLine = [];
for ($i=1; $i<= $monthLong; $i++){
$monthLine[] = date($format, strtotime("first day of -".($monthLong-$i)." month"));
}
return $monthLine;
}
其中的原理,见鸟哥博客分析: http://www.laruence.com/2018/07/31/3207.html
大概原因是 如下规则
以当前传值日期 按照要求处理年月日 如果年月日被处理后超过了合理值,会自动进一位;当月日满进月位, 当年月满进年位
试下几个代码就知道问题了
var_dump(date("Y-m-d", strtotime("2019-02-31")));
# 2019-03-03
# 2019年的2月只有28天 日满进月 日取余; 变为2019-03-03 符合
var_dump(date("Y-m-d", strtotime("2019-12-32")));
# 1970-01-01
# 不符合期望 以为会是 12月没有32 进1月 然后月满进年 最后为 2020-01-01
var_dump(date("Y-m-d", strtotime("2019-13-01")));
# 1970-01-01
# 不符合期望 以为会是 1年没有12个月 进1年 最后为 2020-01-01
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2019-08-31"))));
# 2019-07-31 正常日期
var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2019-08-31"))));
# 2019-10-01 9月没有31号,日满进月
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2019-03-27"))));
# 2019-02-27 也并不是评论里所说减去上个月的天数
var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2019-12-31"))));
# 2020-01-31 月满进年
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2020-01-31"))));
# 2019-12-31 月减退年
var_dump(date("Y-m-d", strtotime("2020-01-31 -1 month")));
# 2019-12-31 月减退年
结论如下:
1.进位规则在显示指定被处理的日期时, 日进位退位正常,月退位正常,进位异常,会导致年变成1970
2.进位规则在默认指定被处理日期为当前时, 日月年进位退位均正常