Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP date() and strtotime() return wrong months on 31st

I'm using date()and strtotime() functions to display the next 3 months in a dropdown list.

PHP Code:

   echo date("m/Y",strtotime("+0 months")); 
   echo date("m/Y",strtotime("+1 months"));
   echo date("m/Y",strtotime("+2 months")); 

However, if the script is running when the server date is on 30th or 31st, the next month, which is Feburary, will be displayed as March instead. i.e. the script above is supposed to return

01/2012
02/2012
03/2012

But, instead of that, it actually displays

01/2012
03/2012
03/2012

that is because Feburary doesn't have 30th or 31st, so the script translates "31/02" into "01/03".

I have read the strtotime() page on php.net, this problem has been raised, but there has not been any useful solutions. So can anyone please help me to find a simple way to solve this problem? Thanks in advance!

like image 754
Michael Wu Avatar asked Jan 30 '12 01:01

Michael Wu


1 Answers

As mentioned within the documentation, you should pass the date for the first day of the current month as the second parameter to the strtotime() function:

$base = strtotime(date('Y-m',time()) . '-01 00:00:01');
echo date('m/Y',strtotime('+0 month', $base));
echo date('m/Y',strtotime('+1 month', $base));
echo date('m/Y',strtotime('+2 month', $base));

See that it works: http://ideone.com/eXis9

01/2012

02/2012

03/2012

like image 78
Tadeck Avatar answered Oct 04 '22 18:10

Tadeck