我想获得给定日期+2个月的第一个日期,我正在使用下面的函数来获得。
$date = '2015-12-31';
echo $date = date('1-m-Y', strtotime('+2 month', strtotime($date)));
这一切都很顺利。但对于12月30日,31日,这并没有给出预期的结果。对于日期2015-12-30
,它给出了结果'1-03-2016'
。我知道因为2月有29天,所以给出了这个结果。但预期结果是CCD_ 3。这可以通过编写新函数来解决。但我想使用内置函数。请帮忙。
按照您的方式,将日期转换为所需月份的1号,然后计算。像这样:
<?php
$date = '2015-12-31';
$date = date('1-m-Y', strtotime($date));
echo $date = date('1-m-Y', strtotime('+2 months',strtotime($date)));
你得到:
2016年2月1日
相反,您可以使用first day of +2 months
:
echo $date = date('d-m-Y', strtotime('first day of +2 months',strtotime($date)));
将输出(如您所愿):
2016年2月1日
date('Y-m-d', strtotime('first day of +2 month', strtotime($date)));
first day of
将2015-12-30映射到2015-12-01,然后+2 month
将其映射到2016-02-01。在添加+2个月之前,通过映射到开始日期的第一天,您不必担心短月。