PHP Add Days To Datetime With Example

In this PHP add days to datetime tutorial, I’ll demonstrate how to use PHP’s Date Interval class to add days to a date.

The introduction to Date Interval will be followed by the actual addition.

How to add Days to DateTime in PHP?

There are many ways to add days to $Date. PHP has built-in functions like strtotime() and date add() that make it very easy to do.

Method or Function Use in PHP add days to date

Using the strtotime() Function: The strtotime() Function is used to turn a date-time description in English text into a UNIX timestamp.

Syntax Description for PHP date add

strtotime( $EnglishDateTime, $time_now )

Parameters for date add PHP

This function can take two optional parameters, which have already been mentioned and will be explained below.

  • $EnglishDateTime: This parameter gives the textual English date-time description of the date or time to be returned.
  • $time_now: This parameter gives the timestamp that was used to figure out the value that was returned. It is a parameter that is optional.

Example add date in PHP

<?php
$Date = "2022-10-11";
 
// Add days to date and display it
echo date('Y-m-d', strtotime($Date. ' + 2 days'));
 
?>

The output of the example program above

2022-10-13

date_add() Function

You can add days, months, years, hours, minutes, and seconds with the date add() function.

Syntax Description

date_add(object, interval);

Parameters

This function takes two parameters, which have already been mentioned and are explained below:

  • Object: It tells the function date create() which DateTime object to return.
  • Interval: It tells the DateInterval object what to do.

Example program

PHP program to add days to $Date in PHP using date_add() function.

<?php
$date = date_create("2022-10-11");

date_add($date, date_interval_create_from_date_string("20 days"));

echo date_format($date, "Y-m-d");

?>

Output:

2022-10-31

DateInterval Class in PHP add days to date

The DateInterval class can be used to store a certain amount of time, such as years, months, hours, etc.

This class’s constructor takes the given interval as a string that starts with P.

This P is a symbol for a period. You must also use the letter T for intervals that involve time, such as hours, minutes, and seconds.

In the table below, you’ll find a list of all the characters that can be used to mark certain periods.

CharacterDescription
Yyears
Mmonths
Wweeks (converted into days)
Ddays
Hhours
Mminutes
Sseconds

You may have noticed that the letter M stands for both months and minutes. The letter T, which I talked about earlier, clears up this confusion.

Since minutes represent the time component of our interval, they will be preceded by a T. Here are a few examples to help you understand.

StringTime Interval
P20D20 days
P5Y5 years
P2Y3M2 years and 3 months
PT10M10 minutes
P2Y3MT1H10M2 years, 3 months, 1 hour and 10 minutes

There are two things you need to keep in mind when setting the length.

  • Before PHP 8.0.0, you can’t mix weeks and days together. P1W3D will mean 10 days starting with PHP 8.0.0, but it meant 3 days in earlier versions.
  • When giving the length of time, you have to go from the biggest unit of time to the smallest. This means that years will always come before months, and months will always come before days, etc.

Adding Days to a Date With PHP DateInterval

Now that we know how to set date intervals, we will learn how to add days to a date in PHP.

We can use the DateTime class’s add() method. Here’s what I mean:

<?php
 
$date = new DateTime('2022-11-10');
echo $date->format('M d, Y H:i:s');
// oct 11, 2022 00:00:00
 
$interval = new DateInterval('P18DT6M');
$date->add($interval);
echo $date->format('M d, Y H:i:s');
// Nov 28, 2022 00:10:00
 
?>

We start with the date October 11, 2022, which is stored in the variable $date as a DateTime object.

Adding 17 days and 10 minutes brings us to 00:10:00 on November 28, 2022.

How do I add 1 day to a date?

To add 1 day to date:

  • You can get the day of the month for a given date by using the getDate() method.
  • Set the next day of the month using the setDate() method.
  • The setDate method will give the Date object an extra day.

Summary

In this summary of PHP Add Days To Datetime, We’ve only talked about the add() method, which is used to add something like days or years to a PHP date.

But PHP also has a sub() method that lets you take any length of time away from a date.

Both of these methods change the value of a DateTime object and then return the same object. If you don’t want the original date to change, you might want to use the DateTimeImmutable class.

Also, you may visit or read the other articles for PHP below.

Common use cases for PHP Add Days To Datetime

  • Web application development. Full-stack PHP apps using vanilla PHP or Laravel/Symfony frameworks.
  • WordPress plugin/theme development. Custom functionality for the world’s most popular CMS.
  • API development. REST or GraphQL endpoints serving mobile apps and SPAs.
  • CLI tools. Command-line scripts for cron jobs, data migration, or automation.
  • Legacy code maintenance. PHP powers a large share of the web; understanding it is a durable skill.

Working code example

<?php
declare(strict_types=1);

class UserService {
    public function getGreeting(string $name): string {
        if ($name === "") {
            throw new InvalidArgumentException("Name is required");
        }
        return "Welcome, " . htmlspecialchars($name);
    }
}

$service = new UserService();
echo $service->getGreeting("Alice");
?>

Best practices

  • Enable strict types. declare(strict_types=1) at the top of every file catches type coercion bugs.
  • Use Composer. Modern PHP uses Composer for dependency management, autoloading, and PSR-4 class naming.
  • Follow PSR standards. PSR-12 for coding style, PSR-4 for autoloading, PSR-3 for logging.
  • Write unit tests with PHPUnit. Aim for 70%+ code coverage on business-critical modules.
  • Use static analysis. PHPStan or Psalm catch many bugs before code runs.

Common pitfalls

  • Global state. Overusing global variables makes testing hard. Prefer dependency injection.
  • SQL concatenation. Always use prepared statements. Never concatenate user input into SQL strings.
  • Missing type declarations. Old PHP allowed loose types. Modern PHP encourages strict typing everywhere.
  • Ignoring errors. Set error_reporting(E_ALL) in development. Handle errors explicitly in production.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →

Leave a Comment