modify() : Date modify

Modify a date with relative text

modify() applies a relative date/time expression such as +2 days or next Monday. With DateTime the object changes; with DateTimeImmutable a new object is returned.

$date = new DateTimeImmutable('2026-09-14 10:00:00');
$changed = $date->modify('+2 days 3 hours');
echo $changed->format('Y-m-d H:i:s');

In PHP 8.3+, malformed modification strings throw DateMalformedStringException, so validate or catch exceptions when the expression comes from outside your code.

This is another way to add or subtract a date object with different month , days ,year , hour , minutes , sec etc.
PHP 8.3+ note: the object-oriented DateTime::modify() and DateTimeImmutable::modify() methods throw DateMalformedStringException for an invalid modifier string. Validate or catch exceptions when modifiers come from outside your code.
Here is an example on how to use modify function.
<?php
date_default_timezone_set ("Asia/Kolkata");
$date1=new DateTime("now") ; // current date
echo $date1->format('d-m-Y');
echo "<br>";
$date2=$date1->modify('+5 day');
 echo $date2->format('d-m-Y');
?>
The output is here
20-10-2026
25-10-2026
We can change the highlighted line like this
$date2=$date1->modify('+3 month +5 day -1 year ');
Output of this change is here
20-10-2026
25-01-2026

Including Time

<?php
date_default_timezone_set ("Asia/Kolkata");
$date1=new DateTime("now") ;
echo $date1->format('d-m-Y H:i:s');
echo "<br>";
$date2=$date1->modify('+5 day +6 hours +20 minutes +30 seconds ');
echo $date2->format('d-m-Y H:i:s');
?>
Output is here ( based on today's date and time). Refresh this page and check the changes in time.
20-10-2026 10:37:21
25-10-2026 16:57:51

Using fixed date and leap year

$date = new DateTime('2024-02-29 12:00:00');
$date2=$date->modify('+1 year +5 hours');
echo $date2->format('d-m-Y H:i:s');
Output is here
01-03-2025 17:00:00
PHP Date Functions Timestamp in PHP Displaying calendar for selection of date by user


Subscribe to our YouTube Channel here



plus2net.com











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