Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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

ParameterTypeDescription
$datetimestringThe date as a string; the current moment by default.
$timezone?DateTimeZoneOptional. 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.2025

The 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-30

Notes

The older DateTime class changes the object itself when modify() is called, which silently corrupts dates. Use DateTimeImmutable in new code.

See also

  • date — Formats a date and time.
  • strtotime — Turns a textual date description into a timestamp.
  • checkdate — Checks whether such a date exists.

Related recipes

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.

Thanks for reading!

Donate to the site — we work hard for you.