Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add days to $Date in PHP?
In PHP, you can add days to a date using several methods. The most common approaches are using strtotime() with date() or the object-oriented DateTime functions.
Method 1: Using strtotime() and date()
The simplest approach uses strtotime() to parse date strings and add time intervals ?
<?php
$date = "2019-11-11";
echo "Displaying date...<br>";
echo "Date = $date";
echo "\nDisplaying updated date...<br>";
echo date('Y-m-d', strtotime($date. ' + 20 days'));
?>
Displaying date... Date = 2019-11-11 Displaying updated date... 2019-12-01
Method 2: Using DateTime Functions
For more object-oriented approach, use date_create(), date_add(), and date_format() functions ?
<?php
$date = date_create("2019-11-11");
echo "Displaying Date...";
echo date_format($date,"Y/m/d");
date_add($date, date_interval_create_from_date_string("25 days"));
echo "\nDisplaying Updated Date...";
echo "<br>".date_format($date, "Y/m/d");
?>
Displaying Date...2019/11/11 Displaying Updated Date... 2019/12/06
Method 3: Using DateTime Class
The modern approach uses the DateTime class with the add() method ?
<?php
$date = new DateTime("2019-11-11");
echo "Original Date: " . $date->format('Y-m-d') . "<br>";
$date->add(new DateInterval('P15D')); // P15D means 15 days
echo "After adding 15 days: " . $date->format('Y-m-d');
?>
Original Date: 2019-11-11 After adding 15 days: 2019-11-26
Comparison
| Method | Ease of Use | Object-Oriented | Best For |
|---|---|---|---|
strtotime() |
Very Easy | No | Simple date calculations |
| DateTime Functions | Moderate | No | Legacy code compatibility |
| DateTime Class | Easy | Yes | Modern applications |
Conclusion
Use strtotime() for simple date additions, while the DateTime class is recommended for modern PHP applications due to its object-oriented nature and better error handling.
Advertisements
