In PHP, date_create_immutable() builds a new DateTimeImmutable object from a date and time string. If the string cannot be parsed, it returns false.
A DateTimeImmutable never changes after it is created. Methods like add(), sub() and modify() return a new object and leave the original untouched, which prevents many hard to find bugs. date_create_immutable() is the procedural form of new DateTimeImmutable(), but it returns false instead of throwing an exception.
Syntax
Call date_create_immutable() with the values you need. Start with this line.
Returns an immutable object for midnight on January 15, 2024.
date_create_immutable('2024-01-15 +1 month')
Understands relative text and returns February 15, 2024.
date_create_immutable('2024-01-15', new DateTimeZone('UTC'))
Reads the string in the UTC timezone.
Use DateTimeImmutable when teaching or writing modern PHP. Remember to store the result of every change, for example $new = $date->modify('+1 day'). The old procedural helpers date_add(), date_sub() and date_date_set() only accept DateTime, but date_format() and date_diff() accept both.
Optional. A date and time string that PHP can parse. The default is "now", which is the current time.
timezone
Optional. A DateTimeZone object. It is ignored if the string has its own timezone or is a Unix timestamp such as '@1705314600'. If null, the default timezone is used.
Return Value
Return Value
Description
DateTimeImmutable
A new immutable date object when the string could be parsed.
false
Returned when the string cannot be parsed.
PHP Examples
Example 1 — Creating an Immutable Date
Create a DateTimeImmutable and change it with modify(). The original value stays the same and the change appears in a new object.
addDays() accepts a DateTimeImmutable and builds an interval such as P30D.
$d->add() returns a new object, so the original date is not touched.
After the call, $start is still 2024-01-15 and $later is 2024-02-14.
The D format prints the short weekday, and February 14, 2024 is a Wednesday.
Frequently Asked Questions
It creates a DateTimeImmutable object from a date string. The object cannot be changed after creation, and every change returns a new object.
date_create() returns a DateTime that is modified in place by methods such as add() and modify(). date_create_immutable() returns a DateTimeImmutable, where those methods return new objects and leave the original alone.
Because it returns a new object instead of changing the old one. Store the result in a variable, like $next = $date->modify('+1 day').
No. date_add() only accepts DateTime. Call $immutable->add($interval) instead. Functions such as date_format() and date_diff() accept both classes.
It returns false when the string cannot be parsed. new DateTimeImmutable() throws an exception instead, so pick the style that fits your error handling.