The DateTimeImmutable Class
The DateTimeImmutable
class is the immutable analogue of DateTime
. It creates a new object with any modification, making it more predictable and safe to work with.
Current Moment in Time
Let's create a DateTimeImmutable
object
with the current date and time:
<?php
$date = new DateTimeImmutable();
?>
Specific Date
Let's create a DateTimeImmutable
object with a specified date:
<?php
$date = new DateTimeImmutable('2025-12-31');
?>
Specific Date and Time
Let's create a DateTimeImmutable
object
with a specified date and time:
<?php
$date = new DateTimeImmutable('2025-12-31 12:59:59');
?>
Formatting Output
The created date can be output in a specified format
using the format
method. Let's do
this for the current moment in time:
<?php
$date = new DateTimeImmutable();
echo $date->format('Y-m-d H:i:s');
?>
Result (will change depending on the moment of execution):
'2025-11-15 14:25:00'
Formatting a Specified Date
Let's format a specified date:
<?php
$date = new DateTimeImmutable('2025-12-31');
echo $date->format('d.m.Y');
?>
Code execution result:
'31.12.2025'
Adding an Interval
Adding an interval to a date
is done via the add
method:
<?php
$date = new DateTimeImmutable('2025-05-15');
$interval = new DateInterval('P10D'); // 10 days
$newDate = $date->add($interval);
echo $newDate->format('Y-m-d');
?>
Code execution result:
'2025-05-25'
Subtracting an Interval
Subtracting an interval from a date
is done via the sub
method:
<?php
$date = new DateTimeImmutable('2025-05-15');
$interval = new DateInterval('P1M2D'); // 1 month and 2 days
$newDate = $date->sub($interval);
echo $newDate->format('Y-m-d');
?>
Code execution result:
'2025-04-13'
Setting a New Date
You can set a new date for a
DateTimeImmutable
object. This is done
via the setDate
method:
<?php
$date = new DateTimeImmutable();
$newDate = $date->setDate(2024, 12, 31);
echo $newDate->format('Y-m-d');
?>
Code execution result:
'2024-12-31'
Setting Time
You can set a new time for a
DateTimeImmutable
object. This is done
via the setTime
method:
<?php
$date = new DateTimeImmutable();
$newDate = $date->setTime(15, 30, 0);
echo $newDate->format('H:i:s');
?>
Code execution result:
'15:30:00'
Comparing Dates
You can compare date objects:
<?php
$date1 = new DateTimeImmutable('2025-01-01');
$date2 = new DateTimeImmutable('2025-02-01');
if ($date1 < $date2) {
echo '+++';
} else {
echo '---';
}
?>
Creating an Object with a Timezone
When creating a DateTimeImmutable
object,
you can specify a timezone:
<?php
$timeZone = new DateTimeZone('Europe/Moscow');
$date = new DateTimeImmutable('2025-12-31 23:59:59', $timeZone);
echo $date->format('Y-m-d H:i:s e');
?>
Code execution result:
'2025-12-31 23:59:59 Europe/Moscow'
See Also
-
the
DateInterval
class,
which specifies a time interval -
the
DateTimeZone
class,
which specifies a timezone