Explain it simply
Dates and times in plain language
A date and time is really two questions glued together: 'which moment?' and 'what does the clock on the wall say there?'. A flight lands at one single moment, yet the person waiting in Yangon and the person waiting in New York read different clocks.
PHP works the same way. You keep the exact moment, and only when you show it to a person do you read it through that person's time zone. Saying 'today' without choosing a time zone is like saying 'today' without saying where.
Problem → Why → Solution
The problem: code that depends on the server's clock
A shop prints 'order placed on' with date('Y-m-d'). It looks right on the developer's laptop in Yangon, but on a server running UTC an order placed at 01:00 in the morning in Yangon shows yesterday's date. Elsewhere a format string written as 'H:m' prints the month where the minutes should be.
Two more problems concern testing. Code that prints the current time cannot be asserted against an exact answer, because the answer changes on every run. And treating '30 days' as 30 * 86400 seconds drifts by an hour in zones that observe daylight saving time.
<?php
// Looks fine, but every line depends on the server's clock and settings.
echo 'Today is ' . date('Y-m-d') . "\n";
echo 'Order ID: ORD-' . date('Ymd-His') . "\n";
echo 'Time: ' . date('H:m') . "\n"; // month in the minutes slot!
$expires = time() + 30 * 86400; // "30 days" ignores DSTWhy dates deserve proper objects
date() returns a bare string and hides which time zone and which moment it used. A DateTimeImmutable keeps both the moment and the time zone together, so when you calculate, PHP applies the calendar and daylight-saving rules for you. And a date handed to a function can no longer be changed behind your back.
Core concept: one instant, many readings
Two ideas get tangled: an instant and a wall-clock reading. An instant is one exact moment in the world. PHP represents it as a Unix timestamp, the number of seconds since 1970-01-01 00:00:00 UTC, and 1773567000 is the same moment everywhere on Earth. A wall-clock reading such as '16:00' only means something together with a time zone. 2026-03-15 09:30 UTC, 16:00 in Yangon (UTC+6:30) and 05:30 in New York (UTC-4 on that date) are three readings of one instant.
That is why the common policy is: store and calculate in UTC, and convert to the reader's zone only when displaying. Keep UTC in database columns and logs, pass timestamps or ISO 8601 strings (DATE_ATOM) between systems, and call setTimezone just before format(). For the class, use DateTimeImmutable with an explicit time zone.
The date() function formats a timestamp in the default time zone (date_default_timezone_get()), and with no argument it reads the current clock, so the same code prints different things on different servers and at different moments. DateTimeImmutable never changes: modify(), setTime(), setTimezone() and add() each return a new object, so a date handed to a function cannot be changed behind your back. The older DateTime changes itself in place, which is the source of many 'why did my start date move?' bugs.
| Format character | Meaning |
|---|---|
| Y, m, d | four-digit year, month (01-12), day (01-31) |
| H, i, s | hour in 24-hour form, minutes, seconds |
| h, A | hour in 12-hour form with AM or PM |
| T, P | time zone abbreviation (EDT) and offset (+06:30) |
| o, W | ISO week-numbering year and week number |
diff() returns a DateInterval: its days property is the total number of whole days, while d, h and i are the leftover parts. modify() accepts relative phrases such as '+3 days', 'next monday' or 'last day of next month'. When you read text typed by a visitor, parse it with createFromFormat and a known format instead of guessing with strtotime, because the format tells PHP exactly what each part means.
- Pick one instant (store it in UTC)
- Attach a time zone to read it
- Format only when displaying
- Each change returns a new object
After format() you only have text, so never do arithmetic on that string.
General pattern
$zone = new DateTimeZone('Region/City');
$when = new DateTimeImmutable('YYYY-MM-DD HH:MM:SS', $zone);
$later = $when->modify('+N days'); // a new object
$local = $when->setTimezone($otherZone); // same instant, other clock
$gap = $when->diff($later); // a DateInterval
echo $local->format('Y-m-d H:i T');Build the object together with its time zone, let each calculation return a new object, and call format() only at the very end when showing the result.
Worked example: one booking seen from three clocks
A booking is stored as 2026-03-15 09:30 UTC. The time is written into the code, so the output is identical on every run. The code below reads that instant through the Yangon and New York clocks, calculates a deadline, and proves that the booking itself did not change.
<?php
$utc = new DateTimeZone('UTC');
$booking = new DateTimeImmutable('2026-03-15 09:30:00', $utc);
$yangon = $booking->setTimezone(new DateTimeZone('Asia/Yangon'));
$newYork = $booking->setTimezone(new DateTimeZone('America/New_York'));
echo 'UTC : ', $booking->format('Y-m-d H:i T'), "\n";
echo 'Yangon : ', $yangon->format('Y-m-d H:i T'), "\n";
echo 'New York : ', $newYork->format('Y-m-d H:i T'), "\n";
$same = $yangon->getTimestamp() === $booking->getTimestamp();
echo 'Same instant: ', var_export($same, true), "\n";
echo '12-hour clock in Yangon: ', $yangon->format('h:i A'), "\n";
echo 'Order ID: ORD-', $booking->format('Ymd-His'), "\n";
$deadline = $booking->modify('+3 days')->setTime(17, 0);
echo 'Deadline : ', $deadline->format('D, d M Y H:i'), "\n";
echo 'Booking still: ', $booking->format('Y-m-d H:i'), "\n";
$left = $booking->diff($deadline);
echo 'Time left: ', $left->days, ' days, ', $left->h, ' hours, ';
echo $left->i, " minutes\n";Code breakdown
- Fixed instant with a zone
$booking = new DateTimeImmutable('2026-03-15 09:30:00', $utc);The second constructor argument says which time zone to read the text in. Because the time is given explicitly, nothing reads 'now' and the result stays stable.
- Same instant, other clock
$yangon = $booking->setTimezone(new DateTimeZone('Asia/Yangon'));setTimezone does not move the instant; it only changes the clock used to read it. So 09:30 UTC becomes 16:00 +0630 and the timestamp stays the same.
- Format characters
echo 'UTC : ', $booking->format('Y-m-d H:i T'), "\n";T prints the time zone abbreviation. A zone without a common abbreviation, like Yangon, prints an offset such as +0630, while New York prints EDT because daylight saving time is in effect on that date.
- Chain modifications
$deadline = $booking->modify('+3 days')->setTime(17, 0);Each method returns a new object, so the calls chain. $booking itself never changes, which is why the code prints 'Booking still' afterwards to prove it.
- diff for the gap
$left = $booking->diff($deadline);diff() returns a DateInterval. days is the total number of days (3), h the leftover hours (7) and i the leftover minutes (30).
UTC : 2026-03-15 09:30 UTC
Yangon : 2026-03-15 16:00 +0630
New York : 2026-03-15 05:30 EDT
Same instant: true
12-hour clock in Yangon: 04:00 PM
Order ID: ORD-20260315-093000
Deadline : Wed, 18 Mar 2026 17:00
Booking still: 2026-03-15 09:30
Time left: 3 days, 7 hours, 30 minutesDateTime versus DateTimeImmutable
The difference shows up inside a single function. A helper called nextDay() seems to add one day, but if it accepts a DateTime it also changes the caller's variable, because both names point at the same object. With the immutable version the original date stays exactly as it was.
<?php
$tz = new DateTimeZone('UTC');
function nextDayMutable(DateTime $d): DateTime
{
return $d->modify('+1 day');
}
function nextDayImmutable(DateTimeImmutable $d): DateTimeImmutable
{
return $d->modify('+1 day');
}
$start = new DateTime('2026-03-15', $tz);
$end = nextDayMutable($start);
echo 'DateTime: start=', $start->format('Y-m-d'), ' end=';
echo $end->format('Y-m-d'), "\n";
$start = new DateTimeImmutable('2026-03-15', $tz);
$end = nextDayImmutable($start);
echo 'DateTimeImmutable: start=', $start->format('Y-m-d'), ' end=';
echo $end->format('Y-m-d'), "\n";DateTime: start=2026-03-16 end=2026-03-16
DateTimeImmutable: start=2026-03-15 end=2026-03-16Look at the first line, where start has moved from the 15th to the 16th. That kind of bug is hard to find in invoice and booking calculations. With DateTime you can clone before changing, but choosing DateTimeImmutable from the start removes the whole class of problem.
A day is not always 24 hours
In New York the clocks jump from 02:00 to 03:00 on the night of 8 March 2026 (spring forward), so that day has only 23 hours. A calendar day and 24 elapsed hours are different things, which is why PHP has two kinds of interval: P1D and PT24H. A wall-clock time that gets skipped, such as 02:30 that night, is moved forward by an hour instead.
<?php
$ny = new DateTimeZone('America/New_York');
$start = new DateTimeImmutable('2026-03-07 12:00:00', $ny); // clocks jump the next night
$ends = [
'P1D (calendar day)' => $start->add(new DateInterval('P1D')),
'PT24H (24 hours)' => $start->add(new DateInterval('PT24H')),
];
foreach ($ends as $label => $end) {
$hours = ($end->getTimestamp() - $start->getTimestamp()) / 3600;
echo str_pad($label, 20), $end->format('Y-m-d H:i T'), ' elapsed: ', $hours, "h\n";
}
$gap = new DateTimeImmutable('2026-03-08 02:30:00', $ny); // this time never happens
echo 'Skipped 02:30 becomes ', $gap->format('H:i T'), "\n";P1D (calendar day) 2026-03-08 12:00 EDT elapsed: 23h
PT24H (24 hours) 2026-03-08 13:00 EDT elapsed: 24h
Skipped 02:30 becomes 03:30 EDTUse P1D for the everyday meaning of 'same time tomorrow', and PT24H only when you really mean exactly 24 hours from now. UTC has no daylight saving time, so doing the arithmetic in UTC sidesteps the difference entirely.
Parsing a visitor's date safely
createFromFormat('Y-m-d', '2026-02-30') does not throw. It overflows to 2026-03-02 and returns a DateTimeImmutable, recording only a warning on the side. You therefore have to inspect getLastErrors() afterwards. A ! at the start of the format fills every part you did not mention with zeros, so the current clock time does not sneak in.
<?php
function parseDate(string $text): ?DateTimeImmutable
{
$utc = new DateTimeZone('UTC');
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $text, $utc);
$problems = DateTimeImmutable::getLastErrors();
if ($date === false) {
return null;
}
if ($problems !== false) {
$issues = $problems['warning_count'] + $problems['error_count'];
if ($issues > 0) {
return null;
}
}
return $date;
}
foreach (['2026-03-15', '2026-02-30', '15/03/2026', 'tomorrow'] as $text) {
$date = parseDate($text);
echo str_pad($text, 12), $date ? $date->format('l, j F Y') : 'invalid', "\n";
}2026-03-15 Sunday, 15 March 2026
2026-02-30 invalid
15/03/2026 invalid
tomorrow invalidSince PHP 8.2 getLastErrors() returns false when nothing went wrong, so the code handles both false and an array. You can validate in other ways too: format the parsed date back with the same format and compare it with the original text, or call checkdate().
Traps in formats and month arithmetic
The code below holds three traps. 'H:m' reads m as the month, so it prints the month where the minutes should be. Y is the calendar year while o is the ISO week-numbering year, so 29 December 2025 is 2025 by Y but week 1 of 2026 by ISO rules. And '+1 month' from 31 January aims at 31 February, which does not exist, and lands on 3 March.
<?php
$utc = new DateTimeZone('UTC');
$t = new DateTimeImmutable('2026-03-15 09:30:00', $utc);
echo 'H:m (wrong) ', $t->format('H:m'), ' H:i (right) ', $t->format('H:i'), "\n";
$edge = new DateTimeImmutable('2025-12-29', $utc);
echo 'Y-m-d: ', $edge->format('Y-m-d'), ' ISO week: ', $edge->format('o-\WW'), "\n";
$jan31 = new DateTimeImmutable('2026-01-31', $utc);
echo '+1 month : ', $jan31->modify('+1 month')->format('Y-m-d'), "\n";
$monthEnd = $jan31->modify('last day of next month');
echo 'last day of next : ', $monthEnd->format('Y-m-d'), "\n";H:m (wrong) 09:03 H:i (right) 09:30
Y-m-d: 2025-12-29 ISO week: 2026-W01
+1 month : 2026-03-03
last day of next : 2026-02-28In real projects
Dates and times in real projects
Dates are everywhere in orders and bookings, invoice due dates, password-reset tokens that expire after fifteen minutes, subscription renewals, scheduled jobs and audit logs. The usual route is to store UTC in the database, for example in a timestamp column or a datetime column you treat as UTC, and convert to the user's time zone only for display.
APIs exchange ISO 8601 strings (DATE_ATOM), so every client can read the offset. For tests, accept 'now' as a parameter instead of calling new DateTimeImmutable() inside the function; the test can then pass a fixed date and assert an exact answer. That is also why every example in this lesson uses a fixed date.
Common mistakes
Common mistakes with dates and times
Assuming the default time zone
date() and strtotime() use date_default_timezone_get(), which depends on php.ini. Moving to another server can change the dates you display, so pass a DateTimeZone explicitly in code.
Using +1 month near month end
Adding +1 month to 31 January gives 3 March, not 28 February. Use 'last day of next month' when you want the end of the month, or clamp the day yourself.
Mixing up H:m and Y
m is the month and i is the minutes, so H:m prints the month in the minutes slot. When you print a week number, use o instead of Y, or the days around New Year show the wrong year.
Passing a mutable DateTime between functions
Calling modify() on a DateTime that was passed in also changes the caller's date. Use DateTimeImmutable, or clone before changing.
Treating a day as 86400 seconds
In zones with daylight saving a day can have 23 or 25 hours. Use P1D for 'same time tomorrow' and PT24H only for exactly 24 hours.
Best practices
Best practices
- Choose DateTimeImmutable from the start and always pass a DateTimeZone explicitly.
- Store and calculate in UTC, and use setTimezone and format only at the display step.
- Accept 'now' as a parameter instead of reading the clock inside a function, so tests can use a fixed date.
- Parse visitor dates with createFromFormat and one explicit format, then check getLastErrors().
Mini challenge
Mini challenge: monthly renewal dates
A subscription starts on 31 January. The monthly renewal falls on the 31st when the month has one, and on the last day of the month otherwise. Write addMonthsClamped(), find the next three renewal dates, and also show the first renewal in Yangon time.
- Write addMonthsClamped(DateTimeImmutable $date, int $months): DateTimeImmutable
- Use immutable objects and never read the current time
- The day must never exceed the length of the target month (use min())
- Print three renewals as Y-m-d and show the first in Asia/Yangon with H:i and T
<?php
function addMonthsClamped(DateTimeImmutable $date, int $months): DateTimeImmutable
{
// TODO: remember the day number, then move to the 1st of the month
// TODO: add the months, and find how many days the target month has
// TODO: return the target month with min(day, daysInMonth) as its day
}
$start = new DateTimeImmutable('2026-01-31 08:00:00', new DateTimeZone('UTC'));
// TODO: print renewal 1, 2 and 3 as Y-m-d
// TODO: print the first renewal converted to Asia/Yangon (Y-m-d H:i T)Expected: Renewal 1 is 2026-02-28, renewal 2 is 2026-03-31, renewal 3 is 2026-04-30, and the first renewal in Yangon prints as 2026-02-28 14:30 +0630.
Show hint
Use modify('first day of this month') first and add the months afterwards, so nothing overflows. format('t') gives the number of days in that month and setDate(year, month, day) puts the day back.
Show solution
<?php
function addMonthsClamped(DateTimeImmutable $date, int $months): DateTimeImmutable
{
$day = (int)$date->format('j');
$firstOfTarget = $date->modify('first day of this month')
->modify(sprintf('%+d months', $months));
$daysInMonth = (int)$firstOfTarget->format('t');
return $firstOfTarget->setDate(
(int)$firstOfTarget->format('Y'),
(int)$firstOfTarget->format('n'),
min($day, $daysInMonth)
);
}
$start = new DateTimeImmutable('2026-01-31 08:00:00', new DateTimeZone('UTC'));
foreach ([1, 2, 3] as $n) {
echo 'renewal ', $n, ': ', addMonthsClamped($start, $n)->format('Y-m-d'), "\n";
}
$first = addMonthsClamped($start, 1)->setTimezone(new DateTimeZone('Asia/Yangon'));
echo 'first renewal in Yangon: ', $first->format('Y-m-d H:i T'), "\n";Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Store one instant in UTC and use setTimezone only when displaying it as the reader's clock.
- DateTimeImmutable never changes, so modify, add and setTime return new objects and protect you from surprise date shifts.
- P1D is a calendar day and PT24H is exactly 24 hours, which differ in zones with daylight saving; +1 month can also overflow at month end.
- Parse visitor dates with createFromFormat, check getLastErrors(), and pass 'now' in as a parameter so tests can use a fixed date.
PHP Language Reference — PHP Documentation Group