Home > Backend Development > PHP Tutorial > Why Does Adding a Day to a Date Not Roll Over to the Next Month?

Why Does Adding a Day to a Date Not Roll Over to the Next Month?

Linda Hamilton
Release: 2024-11-29 11:35:13
Original
421 people have browsed it

Why Does Adding a Day to a Date Not Roll Over to the Next Month?

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;
Copy after login

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));
Copy after login

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;
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template