Home >Backend Development >PHP Tutorial >How to Correctly Add Days to a Date in PHP?

How to Correctly Add Days to a Date in PHP?

DDD
DDDOriginal
2024-12-25 06:44:09829browse

How to Correctly Add Days to a Date in PHP?

Adding Days to Dates in PHP

The task is to manipulate a date returned from a MySQL query (e.g., "2010-09-17") and increment it by a specified number of days. The goal is to create variables like $Date2, $Date3, etc., that represent subsequent dates.

Incorrect Attempt

The user initially tried the following code:

date('Y-m-d', strtotime($Date. ' + 1 day'))

However, this code resulted in the date before the original date.

Correct Solution

To correctly add days to a date in PHP, it is important to use "days" instead of "day" in the strtotime() function. Here's the corrected code:

echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));

Output

This code correctly outputs the subsequent dates:

2010-09-18
2010-09-19

The above is the detailed content of How to Correctly Add Days to a Date in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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