$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 09-09-26
14-09-26 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)09-09-26 22:24:35
12-15-27 02:29:47 $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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.