PHP strtotime +1 month adding an extra month

Jason picture Jason · Jan 29, 2013 · Viewed 114.3k times · Source

I have a simple variable that adds one month to today:

$endOfCycle = date("Y-m", strtotime("+1 month"));

Today is January 2013, so I would expect to get back 2013-02 but I'm getting 2013-03 instead. I can't figure out why it's jumping to March.

Answer

SDC picture SDC · Jan 29, 2013

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.