date()---求N个月后的1号

date()是常用的PHP函数,求2个月后的1号,我们一般会这么写:

echo date('Y-m-01', strtotime('+2 month'));

这么写大部分情况下是没有问题的,看下面的例子:

echo date('Y-m-01',strtotime('+2 month', strtotime('2015-12-31'))) . "\n";
echo date('Y-m-01',strtotime('+2 month', strtotime('2016-12-31'))) . "\n";
echo date('Y-m-01',strtotime('+2 month', strtotime('2016-07-31'))) . "\n";

执行完,你会发现输出的结果和我们想象的不一样,它们分别输出:

2016-03-01

2017-03-01

2016-10-01

 

我们再看下面的例子:

echo date('Y-m-d',strtotime('+2 month', strtotime('2015-12-31'))) . "\n"; //闰年
echo date('Y-m-d',strtotime('+2 month', strtotime('2016-12-31'))) . "\n"; //非闰年

它们分别输出:

2016-03-02

2017-03-03

 

这样我们就明白了,2015-12-31,加上两个月是 2016-02-31,但是2016年的2月份只有29天怎么办呢?往后顺延两天,得到2016-03-02,其他同理,所以在29-31号获取两个月后1号的时候都有可能出现错误。

 

这样我们想得到两个月后的1号,就得这么写:

echo date('Y-m-01',strtotime('+2 month', strtotime(date('Y-m-01',strtotime('2016-07-31'))))) . "\n";

更简单的方法这么写:

echo date('Y-m-01',strtotime('first day of +2 month', strtotime('2016-07-31'))) . "\n";

 

posted @ 2019-03-08 13:51  沙漠海123  阅读(174)  评论(0)    收藏  举报