PHP strtotime的BUG解决
比来应用了strtotime连系-1 month, +1 month, next month猎取上个月或许下个月的日期,不外刚看到一篇文章,才晓得原来应用strtotime间接猎取日期仍是有点小BUG
BUG
如日期:
$today = '2020-12-31'; echo date("Y-m-d",strtotime("$today -1 month"))
输入
2020-12-01
依据下面的输入能够看进去,输入的仍是2020年12月
剖析:
先做-1 month, 那末以后是07-31, 减去一当前就是06-31.
再做日期标准化, 由于6月不31号, 以是就如同2点60等于3点同样, 6月31就等于了7月1
是否是逻辑很”明晰”呢? 咱们也能够手动验证第二个步骤, 比方:
var_dump(date("Y-m-d", strtotime("2020-12-31"))); // 输入2020-12-01
也就是说, 只需触及到巨细月的最初一天, 均可能会有这个蛊惑, 咱们也能够很轻松的验证相似的其余月份, 印证这个论断:
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2020-12-31")))); // 输入2020-12-03 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2020-08-31")))); // 输入2020-10-01 var_dump(date("Y-m-d", strtotime("next month", strtotime("2020-01-31")))); // 输入2020-03-03 var_dump(date("Y-m-d", strtotime("last month", strtotime("2020-03-31")))); // 输入2020-03-03
处理计划
从PHP5.3开端呢, date新增了一系列修改短语, 来明白这个成绩, 那就是”first day of” 以及 “last day of”, 也就是你能够限定好没有要让date主动”标准化”:
var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2020-03-31")))); //输入2020-02-28 var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2020-08-31")))); //输入2020-09-01 var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2020-01-31")))); //输入2020-02-01 var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2020-03-31")))); //输入2020-02-28
那假如是5.3以前的版本, 能够应用mktime之类的, 把一切的日子疏忽掉, 比方都限定为每个月1号就能够了, 只不外就没有如间接用first day来的愈加优雅.
保举教程:《PHP视频教程》
以上就是解决PHP strtotime的BUG的具体内容,更多请存眷资源魔其它相干文章!
标签: php开发教程 php开发资料 php开发自学 strtotime
抱歉,评论功能暂时关闭!