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";

 

转载于:https://www.cnblogs.com/shamohai/p/10495381.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值