DateTime and DateTimeImmutable
PHP's DateTime classes handle time zones, formatting, parsing, intervals, and arithmetic correctly. DateTimeImmutable ensures date calculations never accidentally mutate the original — a lesson learned from years of DateTime bugs.
// DateTimeImmutable — every operation returns a new instance
$now = new DateTimeImmutable();
$nextWeek = $now->modify('+1 week'); // $now is unchanged
$formatted = $now->format('Y-m-d H:i'); // "2026-03-12 14:30"
// Time zone handling — built in, not bolted on
$ny = new DateTimeImmutable('now', new DateTimeZone('America/New_York'));
$tokyo = $ny->setTimezone(new DateTimeZone('Asia/Tokyo'));
echo $tokyo->format('H:i'); // Correct local time in Tokyo
// Intervals and periods
$interval = new DateInterval('P30D'); // 30 days
$future = $now->add($interval);
$diff = $future->diff($now);
echo $diff->days; // 30
// Date periods — iterate over date ranges
$period = new DatePeriod(
new DateTimeImmutable('2026-01-01'),
new DateInterval('P1M'),
new DateTimeImmutable('2026-12-31'),
);
foreach ($period as $month) {
echo $month->format('F Y') . "\n"; // "January 2026", "February 2026", ...
}
// Parse anything
$parsed = DateTimeImmutable::createFromFormat('d/m/Y', '12/03/2026');
The distinction between phpDateTimeImmutable and phpDateTime is one of PHP's best design decisions. Use DateTimeImmutable everywhere and date-related bugs virtually disappear.
Significance: Correctness
Date and time handling is one of programming's hardest problems (time zones, daylight saving, leap seconds). PHP's DateTime classes handle these correctly out of the box, and DateTimeImmutable prevents the mutation bugs that plagued the mutable DateTime class.