在接下来的12个月内获得当天

时间:2014-05-09 10:02:57

标签: php date

有可能在未来12个月内获得当天的日期吗?

看看这些情景:

Today is 2014-05-09
next month will be 2014-06-09
and so on and so fourth

what if today is 2014-01-31
next month is 2014-02-28

Other examples
what if today is 2014-05-31
next month will be 2014-06-30

感谢

2 个答案:

答案 0 :(得分:0)

您可以在给定日期添加DateInterval。但是你的例子中没有统一的逻辑。

例如:

$date = new DateTime( '2014-01-31' );
$aMonthLater = clone $date;
$aMonthLater->add( new DateInterval( 'P1M' ) );


var_dump(
    $date->format( DateTime::ISO8601 ),
    $aMonthLater->format( DateTime::ISO8601 )
);

这将产生如下输出:

2014-01-31T00:00:00+01:00
2014-03-03T00:00:00+01:00

因此,添加一个月实际上会增加一个月 - 例如(从2014-01-31跳到2014-02-28)不会增加整整一个月。

请参阅DateTime::add()

答案 1 :(得分:0)

尝试这个。即使日期是月的最后一天也会正常工作

$date = "2013-03-31";

$d1 = explode("-",$date);

$i = 0;

while ($i < 12)
{

$j = $d1[2];

if(cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) < $d1[2])
$j = cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) ;

echo $d1[0]."-".$d1[1]."-".$j."<br>";

$d1[1]++;

if($d1[1] == 13)
{
$d1[0]++;
$d1[1] = 1;
}
$i++;

if($d1[1] < 10)
$d1[1]="0".$d1[1];

}