date(), DateTimeImmutable, and TimezonesPHP date and time functions let you format timestamps, calculate expiration windows, and convert dates across user timezones. While date() and strtotime() work for quick formatting, modern PHP applications rely on DateTimeImmutable and DateTimeZone for safe date math.
date() vs DateTimeImmutableAlways set a default timezone (usually 'UTC') in your bootstrap code or php.ini so server timestamps stay consistent across deployments. Store dates in UTC in your database and convert to the user's local timezone only when displaying them.
<?php
declare(strict_types=1);
$utcZone = new DateTimeZone('UTC');
$dhakaZone = new DateTimeZone('Asia/Dhaka');
$createdAt = new DateTimeImmutable('now', $utcZone);
$expiresAt = $createdAt->modify('+7 days');
$localView = $createdAt->setTimezone($dhakaZone);
echo "Stored (UTC): " . $createdAt->format('Y-m-d H:i:s') . PHP_EOL;
echo "Expires (UTC): " . $expiresAt->format('Y-m-d H:i:s') . PHP_EOL;
echo "Dhaka Display: " . $localView->format('M j, Y g:i A') . PHP_EOL;
Because DateTimeImmutable returns a new instance whenever you call modify() or setTimezone(), $createdAt never changes accidentally mid-function.
When parsing dates from APIs or forms, use DateTimeImmutable::createFromFormat() so ambiguous inputs like 04/05/2026 are never misread as month-first versus day-first.
<?php
declare(strict_types=1);
$invoiceDate = DateTimeImmutable::createFromFormat('!Y-m-d', '2026-11-01', new DateTimeZone('UTC'));
$dueDate = DateTimeImmutable::createFromFormat('!Y-m-d', '2026-11-15', new DateTimeZone('UTC'));
if ($invoiceDate && $dueDate) {
$diff = $invoiceDate->diff($dueDate);
echo "Payment window: {$diff->days} days" . PHP_EOL;
}
DateTime when calculating intervals: Calling $date->modify('+1 day') on a mutable DateTime alters the original variable everywhere it is referenced.! prefix in createFromFormat(): Without ! (as in '!Y-m-d'), PHP fills the time portion with the current clock time instead of 00:00:00.86400 seconds to advance one calendar day: Daylight Saving Time transitions have 23-hour or 25-hour days. Use ->modify('+1 day') instead.DateTime and DateTimeImmutable?DateTime mutates the object in place on every modification, while DateTimeImmutable leaves the original intact and returns a modified copy.
Call time() for the current Unix timestamp in seconds, or $dt->getTimestamp() on any DateTimeInterface object.
date('Y-m-d') sometimes show yesterday's date?Your PHP runtime timezone (date_default_timezone_get()) likely defaults to UTC while your local clock is ahead or behind UTC.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.