DateTimeImmutable for Time Zones and Formatting
Lesson 7 of 43 in the PHP 8 learning path.
How do I handle dates in PHP without mutating a shared clock?
A class period has a start, a duration, and a time zone. DateTimeImmutable stores that instant and refuses to change in place. modify() returns a new object, so a shared start time can be handed to several calculations without one of them moving the clock the others still hold. The sample builds 2026-11-26 08:30:00 in Asia/Manila, adds 90 minutes, and prints both values. The original still reads 08:30 after the call, which is the property you want when the same opening time is shown on the roster and used to compute the dismissal time.
The zone is an explicit DateTimeZone, not a guess from the server default. Asia/Manila is a fixed offset of +08:00 with no daylight-saving shift, which makes it a clear classroom example. Format strings should prefer the offset or the zone id.
Syntax & Parameters
$start = new DateTimeImmutable('2026-11-26 08:30:00', new DateTimeZone('Asia/Manila'));
$end = $start->modify('+90 minutes');
Example
<?php
declare(strict_types=1);
final class ClassPeriod
{
public function __construct(
private readonly DateTimeImmutable $start,
private readonly DateTimeImmutable $end,
) {
if ($end <= $start) {
throw new InvalidArgumentException('A class period has to end after it starts.');
}
}
public function start(): DateTimeImmutable
{
return $this->start;
}
public function end(): DateTimeImmutable
{
return $this->end;
}
}
function openPeriod(DateTimeZone $zone, string $localStart, string $modify): ClassPeriod
{
$start = new DateTimeImmutable($localStart, $zone);
$end = $start->modify($modify);
if ($end === false) {
throw new InvalidArgumentException('The class duration could not be applied.');
}
return new ClassPeriod($start, $end);
}
$zone = new DateTimeZone('Asia/Manila');
$period = openPeriod($zone, '2026-11-26 08:30:00', '+90 minutes');
$format = 'Y-m-d H:i P';
echo 'start=' . $period->start()->format($format) . "\n";
echo 'end=' . $period->end()->format($format) . "\n";
echo 'zone=' . $period->start()->getTimezone()->getName() . "\n";
echo 'unchanged=' . $period->start()->format($format) . "\n";
Expected Output
start=2026-11-26 08:30 +08:00 end=2026-11-26 10:00 +08:00 zone=Asia/Manila unchanged=2026-11-26 08:30 +08:00
Line-by-Line Walkthrough
- declare(strict_types=1) type-checks the constructor and openPeriod() calls written in this file.
- ClassPeriod stores two DateTimeImmutable objects and rejects an end that is not later than the start.
- start() and end() return those objects so a caller can format them without a setter that would imply mutation.
- openPeriod() constructs the start in the zone that was passed in, so the wall time 08:30 is Asia/Manila time.
- modify("+90 minutes") returns a new DateTimeImmutable. The $start variable is left on 08:30.
- A false return from modify() is rejected. On current PHP the method returns an object, and the check keeps the contract obvious.
- The period is opened at 2026-11-26 08:30:00 with a 90 minute duration.
- The format Y-m-d H:i P prints the offset +08:00 instead of a timezone abbreviation.
- getTimezone()->getName() prints Asia/Manila, which is the identifier to store beside the schedule.
- The unchanged line prints the original start again, showing that modify() did not move the shared clock.
Common Pitfalls & Security
Mutable DateTime objects are easy to share by accident. A function that calls modify() or setTime() on a clock it received will change the caller value. DateTimeImmutable makes that a new value instead. Time zones are the other half of the bug: a naive "08:30" stored without a zone becomes a different class period when the server default changes.
- DateTime::modify() changes the object you already hold. DateTimeImmutable::modify() returns a different object and leaves the original in place.
- Format code T prints PST for Asia/Manila. That abbreviation collides with US Pacific in a reader mind. Print P or the zone id.
- new DateTimeImmutable($text) with no zone uses the default timezone. Set the zone in the constructor or with an explicit date_default_timezone_set() at the front controller, one time.
- Comparing instants with <= uses the absolute moment, which is what you want for "does this period end after it starts?" Comparing formatted strings breaks across offsets.
- User-supplied modifier strings such as "+90 minutes" are safe only when the modifier comes from your own code. A request field used as a modifier can throw or build a surprising date.
- Storing a local wall time and later formatting it in UTC shifts the roster by eight hours for a Manila campus.
Best Practices & Modern Standards
Use DateTimeImmutable on PHP 8.3 and newer, with an explicit DateTimeZone, for every value that leaves a function. Pass the clock in from the edge of the request so a test can supply 2026-11-26 08:30:00 instead of "now". Format at the view, and keep the object intact in the model.
When the school has one campus, Asia/Manila can be the application zone. When records are shared, store a UTC instant or a string produced by DateTimeInterface::ATOM, and convert to the campus zone only in the template. Avoid strtotime() for user-facing schedules. Its relative phrases and default zone are harder to review than modify() on an immutable value.
Real-World Use
The grade book shows a lab that opens at 08:30 in Manila and runs 90 minutes. The roster page and the dismissal calculation both receive the same DateTimeImmutable start. modify("+90 minutes") produces 10:00 for the dismissal line, and the roster still prints 08:30 because the original object was not edited.
Frequently Asked Questions
Does modify() change a DateTimeImmutable?
It returns a new object. The sample prints unchanged=2026-11-26 08:30 +08:00 after computing the end. Assign the return value, as $end = $start->modify("+90 minutes") does.
Why avoid the T format code for Manila?
PHP prints PST for Asia/Manila, meaning Philippine Standard Time in the timezone database. Readers often read PST as US Pacific. The offset +08:00 or the id Asia/Manila is clearer.
Can I pass an int timestamp into the schedule?
Yes, with care. Create the object from a Unix timestamp in UTC, then convert to Asia/Manila for display. A timestamp has no wall-time zone of its own.
What if modify() receives a bad modifier?
On current PHP a bad modifier throws DateMalformedStringException, which extends DateException. The sample still rejects a false return so the period is only built from a real end instant. Catch the exception at the form boundary and show a validation error.