The sub Method of the DateTime Class
The sub
method of the DateTime
class subtracts the specified time interval from the date. It accepts an object of DateInterval
as a parameter. The date object itself is modified in the process.
Syntax
$datetime->sub(DateInterval $interval);
Example
Subtract 2 days from the current date:
<?php
$date = new DateTime('2023-05-15');
$interval = new DateInterval('P2D');
$date->sub($interval);
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-05-13'
Example
Subtract 1 month and 5 days from the specified date:
<?php
$date = new DateTime('2023-06-20');
$interval = new DateInterval('P1M5D');
$date->sub($interval);
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-05-15'