


Why Does Adding a Day to a Date Not Roll Over to the Next Month?
Nov 29, 2024 am 11:35 AMCorrecting 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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
