Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strtotime +1 month adding an extra month [duplicate]

Tags:

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.

like image 530
Jason Avatar asked Jan 29 '13 13:01

Jason


2 Answers

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.

like image 79
SDC Avatar answered Sep 24 '22 20:09

SDC


This should be

$endOfCycle=date('Y-m-d', strtotime("+30 days")); 

strtotime

expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

while

date

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.

See the manual pages for:

  • http://www.php.net/manual/en/function.strtotime.php
  • http://www.php.net/manual/en/function.date.php
like image 35
One Man Crew Avatar answered Sep 25 '22 20:09

One Man Crew