Question

Is it possible to get the current day in next 12 months?

Take a look at these scenarios:

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

thanks

Was it helpful?

Solution

try this.It will work fine even if date is last day of the month also

$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];

}

OTHER TIPS

You can add a DateInterval to the given date. But there is no unified logic in your examples.

For example:

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


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

This will result in an output like:

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

Thus adding a month will actually add a whole month – you example (skipping from 2014-01-31 to 2014-02-28) does not add a full month.

See DateTime::add()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top