PHP Date / Time
PHP's date handling is split between procedural functions (date(), time(), strtotime()) and an OO API (DateTimeImmutable, DateInterval). Use the OO classes for new code.
Procedural quickies
PHP
echo date('Y-m-d'); // 2026-06-06
echo date('H:i:s'); // 14:32:11
echo time(); // Unix timestamp now
echo strtotime('next monday'); // Parse English-ish dates
The OO API
PHP
$now = new DateTimeImmutable();
$tomorrow = $now->modify('+1 day');
$soon = $now->add(new DateInterval('PT15M')); // +15 min
echo $now->format('c'); // ISO 8601
echo $now->format('Y-m-d H:i');
Immutable vs mutable
| Class | Behaviour |
|---|---|
DateTime | Mutating methods change the object. |
DateTimeImmutable | Methods return a new object — safer. |
Default to DateTimeImmutable — it never surprises a caller who held onto an instance.
Format characters
| Char | Means |
|---|---|
Y / y | 4- / 2-digit year |
m / n | Month — leading zero / no zero |
d / j | Day — leading zero / no zero |
H / G | 24-hr hour — with / without leading zero |
i / s | Minutes / seconds |
D / l | Day name — short / long |
M / F | Month name — short / long |
c | ISO 8601 (e.g. 2026-06-06T14:32:11+00:00) |
U | Unix timestamp |
Time zones
PHP
$tz = new DateTimeZone('Australia/Sydney');
$now = new DateTimeImmutable('now', $tz);
echo $now->format('c');
Tip: Store every timestamp as UTC in the database. Convert to the user's zone only when rendering. The day daylight-saving rolls over, you'll thank past-you.
Example
Example
<?php
echo date('Y-m-d H:i:s'), PHP_EOL;
echo date('Y-m-d', strtotime('+1 week')), PHP_EOL;
$d = new DateTimeImmutable();
echo $d->format('c'), PHP_EOL;
echo $d->modify('+7 days')->format('Y-m-d');
Try it Yourself »
Exercise
Modern immutable datetime class.
new
()
17 chars; PascalCase.
Discussion
Loading…