Correcting Date Addition with Month Rollover
Your code intends to add one day to a date, but it seems to return a date that precedes the addition. Let's delve into the issue and provide a solution that correctly rolls over months upon day addition.
The problematic code:
$stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00")); echo 'date before day adding: '.$stop_date; $stop_date = date('Y-m-d H:i:s', strtotime('+1 day', $stop_date)); echo ' date after adding one day. SHOULD be rolled over to the next month: '.$stop_date;
The error lies in the line where you perform the addition:
$stop_date = date('Y-m-d H:i:s', strtotime('+1 day', $stop_date));
This line uses the strtotime() function to manipulate the date. However, when you specify a time offset like ' 1 day', it does not roll over months correctly.
Solution
To correctly add a day and roll over months when necessary, you can use one of the following approaches:
PHP 5.3 :
$stop_date = '2009-09-30 20:24:00'; echo 'date before day adding: ' . $stop_date; $stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day')); echo 'date after adding 1 day: ' . $stop_date;
PHP 5.2 :
$stop_date = new DateTime('2009-09-30 20:24:00'); echo 'date before day adding: ' . $stop_date->format('Y-m-d H:i:s'); $stop_date->modify('+1 day'); echo 'date after adding 1 day: ' . $stop_date->format('Y-m-d H:i:s');
These solutions will correctly add one day to the specified date and roll over months as needed.
The above is the detailed content of Why Does Adding a Day to a Date Not Roll Over to the Next Month?. For more information, please follow other related articles on the PHP Chinese website!