date_add() : adds a specified interval to a DateTime object

WE will learn how to add date time intervals to a date object. We must understand date interval and date format before using add function to the date object.

PHP version is 5.3 or higher
How to know PHP version installed in your server ?
Procedural style
$date = date_create('2019-01-05');
date_add($date, date_interval_create_from_date_string('15 days'));
echo date_format($date, 'Y-m-d'); // Output is 2019-01-20
Object oriented style.
$date1=new DateTime('2019-05-30'); // date object created. 
$new_date=$date1->add(new DateInterval('P1Y3M')); // inerval of 1 year 3 months 
echo $new_date->format('Y-M-d'); // Output is 2020-Aug-30

Read more on how to prepare DateInterval()

Let us try to add 5 days to current date.
date_default_timezone_set ("Asia/Kolkata");
$date=new DateTime("now") ;
echo $date->format('d-m-y');
echo "<br>";
$date=$date->add(new DateInterval('P5D'));
echo $date->format('d-m-y ');
The output is here
17-10-25
22-10-25
We will add 1 Year, 3 months , 5 days to current date . We will only change the affected row in above code like this.
$date=$date->add(new DateInterval('P1Y3M5D'));
echo $date->format('m-d-y ');
Let us add hour minute and seconds to this date object.

date_default_timezone_set ("Asia/Kolkata");
$date=new DateTime("now") ;
echo $date->format('d-m-y H:i:s');
echo "<br>";
$date=$date->add(new DateInterval('P1Y3M5DT4H5M12S'));
echo $date->format('m-d-y H:i:s ')";
Output is here ( Refresh this page to see the change in output)
17-10-25 19:48:37
01-22-27 23:53:49

Using DateTimeImmutable object

DateTimeImmutable never modifies itself but returns a new object instead
$date1=new DateTime('2019-05-30'); // date object created. 
$date1->add(new DateInterval('P1Y3M')); // inerval of 1 year 3 months added
echo $date1->format('Y-M-d'); // Output is 2020-Aug-30
/// by using DateTimeImmutable ///
$date1=new DateTimeImmutable('2019-05-30'); // date object created . 
$date1->add(new DateInterval('P1Y3M')); // inerval of 1 year 3 months added
echo $date1->format('Y-M-d'); //  Output is 2019-May-30
In case of date object created using DateTimeImmutable after adding the interval the original value never changes.
PHP Date Functions diff(): Difference in two dates
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer