PHP | DateTime add() Function
Last Updated :
10 Oct, 2019
Improve
The DateTime::add() function is an inbuilt function in PHP which is used to add an amount of time (days, months, years, hours, minutes and seconds) to the given DateTime object.
Syntax:
php
php
- Object oriented style:
DateTime DateTime::add( DateInterval $interval )
- Procedural style:
DateTime date_add( DateTime $object, DateInterval $interval )
- $object: It specifies the DateTime object returned by date_create() function. This function returns a new DateTime object.
- $interval: This parameter holds the DateInterval object.
<?php
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
// DateInterval object is taken as the
// parameter of the add() function
// Here 1 day is added
$datetime->add(new DateInterval('P1D'));
// Getting the new date after addition
echo $datetime->format('Y-m-d') . "\n";
?>
<?php
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
// DateInterval object is taken as the
// parameter of the add() function
// Here 1 day is added
$datetime->add(new DateInterval('P1D'));
// Getting the new date after addition
echo $datetime->format('Y-m-d') . "\n";
?>
Output:
Program 2:
2019-10-01
<?php
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
// DateInterval object is taken as the
// parameter of the add() function
// Here 5 hours, 3 Minutes and 10 seconds is added
$datetime->add(new DateInterval('PT5H3M10S'));
// Getting the new date after addition
echo $datetime->format('Y-m-d H:i:s') . "\n";
?>
<?php
// Initialising a DateTime
$datetime = new DateTime('2019-09-30');
// DateInterval object is taken as the
// parameter of the add() function
// Here 5 hours, 3 Minutes and 10 seconds is added
$datetime->add(new DateInterval('PT5H3M10S'));
// Getting the new date after addition
echo $datetime->format('Y-m-d H:i:s') . "\n";
?>
Output:
Reference: https://www.php.net/manual/en/datetime.add.php
2019-09-30 05:03:10