Formatting the current time
PHP
<?php
echo date("Y-m-d"); // 2026-08-22
echo date("d/m/Y"); // 22/08/2026
echo date("H:i:s"); // 14:30:05
echo date("l, jS F Y"); // Saturday, 22nd August 2026Common format characters:
| Char | Means | Example |
|---|---|---|
Y / y |
4- / 2-digit year | 2026 / 26 |
m / n |
month, padded / not | 08 / 8 |
d / j |
day, padded / not | 05 / 5 |
H / h |
hour 24 / 12 | 14 / 02 |
i |
minutes | 30 |
s |
seconds | 05 |
l / D |
weekday full / short | Saturday / Sat |
F / M |
month full / short | August / Aug |
A |
AM/PM | PM |
Timezones
Set the timezone or you'll get UTC:
PHP
<?php
date_default_timezone_set('Asia/Kathmandu');
echo date('H:i'); // now correct for Nepal (UTC+5:45)Timestamps
PHP
<?php
$now = time(); // seconds since 1970
echo date("Y-m-d", $now);
echo strtotime("2026-08-22"); // string → timestamp
echo date("Y-m-d", strtotime("+1 week"));
echo date("Y-m-d", strtotime("tomorrow"));
echo date("Y-m-d", strtotime("last day of this month"));The DateTime class (preferred)
For anything beyond simple formatting, use the object API — it handles timezones and arithmetic correctly:
PHP
<?php
$d = new DateTime('2026-08-22', new DateTimeZone('Asia/Kathmandu'));
echo $d->format('d M Y'); // 22 Aug 2026
$d->modify('+10 days');
echo $d->format('Y-m-d'); // 2026-09-01Difference between two dates
PHP
<?php
$start = new DateTime('2026-01-01');
$end = new DateTime('2026-08-22');
$diff = $start->diff($end);
echo $diff->days; // total days
echo $diff->format('%m months, %d days');Immutable dates
DateTime::modify() changes the object in place, which causes bugs when
the object is shared. DateTimeImmutable returns a new object instead —
prefer it:
PHP
<?php
$a = new DateTimeImmutable('2026-08-22');
$b = $a->modify('+1 day');
echo $a->format('Y-m-d'); // 2026-08-22 — unchanged
echo $b->format('Y-m-d'); // 2026-08-23