Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`strtotime` bug when using + 1 month from January

I' m trying to make a ajax calendar with multiple tabs for a date range previously entered. But for example:

I want get the next month, it prints march instead of february

$start= "2013-01-31";
$current =  date('n', strtotime("+1 month",$start)) //prints 3

I think thats occurs because february 2014 is 28 and add +31 like base from the start month but why?

like image 776
Thiago Masano Cavaloti Avatar asked Feb 14 '23 19:02

Thiago Masano Cavaloti


1 Answers

You're trying to add one month to the date 2013-01-31. It should give 31th Feburary 2013, but since the date doesn't exist, it moves on to the next valid month (which is March).

You can use the following work-around:

$current = date('n', strtotime("first day of next month",strtotime($start)));

Using DateTime class:

$date = new DateTime('2013-01-31');
$date->modify('first day of next month');
echo $date->format('n');

This will correctly output 2.

Demo!

like image 160
Amal Murali Avatar answered Feb 17 '23 11:02

Amal Murali