在开发中经常遇到时间加减操作,今天踩了个坑,记录一下
<?php
echo date('Y-m-d', strtotime('-1 month', '2019-07-31'));
上面这点代码输出什么?一开始我以为是输出2019-06-30
,其实它输出的是 2019-07-01
。
先看看下面这段代码:
<?php
echo date('Y-m-d', strtotime('2019-06-31'));
这样不会报错,执行结果输出2019-07-01
。也就是说, 只要涉及到大小月的最后一天, 都可能会有这个问题。
echo date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31")));
//输出2017-03-03
echo date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31")));
//输出2017-10-01
echo date("Y-m-d", strtotime("next month", strtotime("2017-01-31")));
//输出2017-03-03
echo date("Y-m-d", strtotime("last month", strtotime("2017-03-31")));
//输出2017-03-03
如果之前一直是这样的开发的话,那真的是日乐购,咋整???
从PHP5.3开始, date新增了一系列修正短语, 来明确这个问题, 那就是 first day of
和 last day of
, 也就是你可以限定好不要让 date
自动”规范化”:
下面代码完美解决
echo date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31")));
//输出2017-02-28
echo date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31")));
输出2017-09-01
echo date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31")));
输出2017-02-01
echo date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31")));
输出2017-02-28
如果是5.3之前的版本, 可以使用mktime之类的, 把所有的日子忽略掉, 比如都限定为每月1号就可以了, 只不过就不如直接用first day来的更加优雅
本文参考自令人困惑的strtotime