2

I am facing a strange issue with incrementing date with one month for following case For date input as 2014-01-31 I am getting 2014-03-03 while it should "2014-02-28"

I am using following code

$time = strtotime("2014-01-31");
$final = date("Y-m-d", strtotime("+1 month", $time));

1 Answers1

3

The +1 month in php has unexpected behaviour when you use it at the 30th or 31st of January. You will get a date in March. This is because php online raises the month number by 1 (so 2014-01-31 will become 2014-02-31. This doesn't exist so php will correct this into 2012-02-28 + 3.

This will get you the right result at the end of the month.

$d = new DateTime( '2014-01-31' );
$d->modify( 'last day of +1 month' );
$final = $d->format( 'Y-m-d' );

This is explained at the php manual at: http://php.net/manual/en/function.strtotime.php#107331

vascowhite
  • 18,120
  • 9
  • 61
  • 77
Maisnon
  • 61
  • 1
  • 5