DateTimeImmutable
A date and time object that cannot be changed: every operation returns a new object.
Syntax
new DateTimeImmutable(string $datetime = "now", ?DateTimeZone $timezone = null)Parameters
| Parameter | Type | Description |
|---|---|---|
| $datetime | string | The date as a string; the current moment by default. |
| $timezone | ?DateTimeZone | Optional. The time zone. |
Return value
DateTimeImmutableAn object with the `format()`, `modify()` and `diff()` methods.
Examples
Formatting and shifting a date:
<?php
$date = new DateTimeImmutable('2025-01-30 14:05');
echo $date->format('d.m.Y H:i'), "\n";
echo $date->modify('+7 days')->format('d.m.Y');Output:
30.01.2025 14:05
06.02.2025The difference between dates, and comparing them:
<?php
$start = new DateTimeImmutable('2025-01-01');
$finish = new DateTimeImmutable('2025-03-01');
echo $start->diff($finish)->days, "\n";
var_dump($start < $finish);Output:
59
bool(true)Parsing a date in a known format:
<?php
$date = DateTimeImmutable::createFromFormat('d.m.Y', '30.01.2025');
echo $date->format('Y-m-d');Output:
2025-01-30Notes
The older DateTime class changes the object itself when modify() is called, which silently corrupts dates. Use DateTimeImmutable in new code.
See also
Related recipes
- How to add days to a date
- How to calculate age from a birth date
- How to check whether a date is a weekend
- How to compare two dates
- How to convert a time to another time zone
- How to convert a timestamp to a date and back
- How to get the current date and time
- How to get the day of the week
- How to get the first and last day of a month
- How to show "5 minutes ago"
- How to validate a date
In the tutorial
- Date and time — Working with dates in PHP — the date function, the DateTimeImmutable class, formats, adding to dates and the difference between them.