iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

ClassBehaviour
DateTimeMutating methods change the object.
DateTimeImmutableMethods return a new object — safer.

Default to DateTimeImmutable — it never surprises a caller who held onto an instance.

Format characters

CharMeans
Y / y4- / 2-digit year
m / nMonth — leading zero / no zero
d / jDay — leading zero / no zero
H / G24-hr hour — with / without leading zero
i / sMinutes / seconds
D / lDay name — short / long
M / FMonth name — short / long
cISO 8601 (e.g. 2026-06-06T14:32:11+00:00)
UUnix 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 ()

Test yourself

Q1. Modern OO class for points in time is…
Q2. Format string for ISO 8601 is…
Q3. Best storage zone is…

Discussion

Loading…