DateTimeImmutable

We can use DateTimeImmutable in place of DateTime class when we want the original object is not to be modified.

Using date add ...
$date1=new DateTime('2018-04-23'); // date object created. 
$date1->add(new DateInterval('P1Y3M')); // interval of 1 year 3 months added
echo $date1->format('Y-M-d'); // Output is 2019-Jul-23
/// by using DateTimeImmutable ///
$date1=new DateTimeImmutable('2018-04-23'); // date object created . 
$date1->add(new DateInterval('P1Y3M')); // interval of 1 year 3 months added
echo $date1->format('Y-M-d'); //  Output is 2018-Apr-23
In case of date object created using DateTimeImmutable after adding the interval the original value never changes.

Example: Creating DateTimeImmutable in Different Time Zones

$date = new DateTimeImmutable('now', new DateTimeZone('America/New_York'));
echo $date->format('Y-m-d H:i:s');

Example: Handling Date Modifications

Read more on Date modification by modify()
$date = new DateTimeImmutable('2023-12-25');
$newDate = $date->modify('+1 day');
echo $date->format('Y-m-d');  // Output: 2023-12-25
echo $newDate->format('Y-m-d');  // Output: 2023-12-26

Using today's date

$date = new DateTimeImmutable('now');
$newDate = $date->modify('+1 day');
echo $date->format('Y-m-d : H:i:s').'<br>';  
echo $newDate->format('Y-m-d : H:i:s');  
Output
2025-10-14 : 03:30:31
2025-10-15 : 03:30:31
Using setDate()
$today = new  DateTimeImmutable();
echo $today->format('Y-m-d ').'<br>';
$today->setDate(13,11,2025);
echo $today->format('Y-m-d');
Output
2025-10-14 
2025-10-14


PHP Date Functions setDate() : Set date for date object Timestamp in PHP Displaying calendar for selection of date by user
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



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-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer