The Modify Method of the DateTime Class
The modify
method allows you to modify the date and time of a DateTime
object.
It accepts a string parameter with a relative date format that specifies
how to change the current date/time value.
Syntax
$datetime->modify(string $modifier);
Example
Add 1
day to the current date:
<?php
$date = new DateTime('2023-01-01');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-01-02'
Example
Subtract 2
weeks from the current date:
<?php
$date = new DateTime('2023-01-15');
$date->modify('-2 weeks');
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-01-01'
Example
Set the first day of the next month:
<?php
$date = new DateTime('2023-01-20');
$date->modify('first day of next month');
echo $date->format('Y-m-d');
?>
Code execution result:
'2023-02-01'