phpPHP
Module 41: PHP Date and TimeAdvanced40 min read

DateTimeImmutable, Time Zones (UTC) & DateInterval Calculations

Avoid subtle mutation bugs by using DateTimeImmutable over DateTime, store timestamps in UTC, and perform calendar arithmetic with DateInterval.

Key Takeaways & Core Concepts
  • and convert to user timezone only at display.

DateTimeImmutable, Time Zones (UTC) & DateInterval Calculations

### 1. Always Prefer DateTimeImmutable Calling $dt->modify('+1 day') on mutable DateTime mutates the original object everywhere it is referenced! DateTimeImmutable returns a new instance, eliminating side-effect bugs. Always store dates in UTC and convert to user timezone only at display.

1. DateTimeImmutable & Timezone Conversion
1<?php
2$utc = new DateTimeImmutable('2026-11-29 10:00:00', new DateTimeZone('UTC'));
3$ist = $utc->setTimezone(new DateTimeZone('Asia/Kolkata'));
4$nextWeek = $ist->modify('+7 days');
5echo "IST: " . $ist->format('Y-m-d H:i') . " | +7d: " . $nextWeek->format('Y-m-d') . "\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
5 lines
Note: Converts UTC to Asia/Kolkata without mutating the original `$utc` instance.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)