Date Add

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
31-03-20
05-04-20
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)
31-03-20 03:06:47
07-06-21 07:11:59

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.


plus2net.com






Post your comments , suggestion , error , requirements etc here .




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