The add Method of The DateTime Class
The add
method of the DateTime
class adds a specified time interval to a date.
The method accepts one parameter - an object of DateInterval
, which defines the time period to be added.
Syntax
$datetime->add(DateInterval $interval);
Example
Add 1 day to the current date:
<?php
$date = new DateTime('2023-01-01');
$interval = new DateInterval('P1D');
$date->add($interval);
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-01-02'
Example
Add 1 month, 2 days, and 4 hours to the specified date:
<?php
$date = new DateTime('2023-01-01 12:00:00');
$interval = new DateInterval('P1M2DT4H');
$date->add($interval);
echo $date->format('Y-m-d H:i:s');
?>
Code execution result:
'2023-02-03 16:00:00'
See Also
-
the
date_diff
function,
which calculates the difference between two dates -
the
date_modify
function,
which modifies a timestamp