Log in Sign up

Set the time zone first

date_default_timezone_set('Europe/Berlin');   // or date.timezone in php.ini
echo date_default_timezone_get();

Timestamps and date()

A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.

time();                          // current timestamp
microtime(true);                 // with microseconds (for timing code)
date('Y-m-d H:i:s');             // 2026-11-15 14:37:00
date('d.m.Y', $timestamp);       // 15.11.2026
mktime(12, 0, 0, 12, 24, 2026);  // timestamp: hour, min, sec, month, day, year
checkdate(2, 30, 2026);          // false – validates month, day, year
CharMeaningExample
Y / yyear 4 / 2 digits2026 / 26
m / nmonth with / without zero03 / 3
d / jday with / without zero05 / 5
H / Ghour 24h with / without zero09 / 9
h / Ahour 12h / AM or PM09 / PM
i / sminutes / seconds07 / 30
D / lweekday short / fullSun / Sunday
M / Fmonth short / fullNov / November
Nweekday 1 (Mon) – 7 (Sun)7
WISO week number46
tdays in month30
Utimestamp
cISO 86012026-11-15T14:37:00+01:00

strtotime

Turns English text into a timestamp (returns false on failure).

strtotime('tomorrow');
strtotime('+1 week 2 days');
strtotime('next monday');
strtotime('last day of this month');
strtotime('2026-12-24 18:00');

Objects are safer than timestamps: they carry the time zone and handle daylight saving correctly. DateTimeImmutable returns a new object on every change; DateTime changes itself.

$now   = new DateTimeImmutable();                       // now
$d     = new DateTimeImmutable('2026-12-24 18:00', new DateTimeZone('Europe/Berlin'));
$d2    = DateTimeImmutable::createFromFormat('d.m.Y', '24.12.2026');

echo $d->format('d.m.Y H:i');                           // 24.12.2026 18:00
$next  = $d->modify('+1 month');
$plus  = $d->add(new DateInterval('P1DT2H'));            // +1 day 2 hours
$utc   = $d->setTimezone(new DateTimeZone('UTC'));
echo $d->getTimestamp();

DateInterval format: P + Y M D, then T + H M S – e.g. P1Y2M, PT30M, P2W.

Differences between dates

$a = new DateTimeImmutable('2026-01-01');
$b = new DateTimeImmutable('2026-11-15');
$diff = $a->diff($b);

echo $diff->days;                    // 318 (total days)
echo $diff->m . ' months ' . $diff->d . ' days';
echo $diff->format('%a days');       // 318 days
echo $diff->invert;                  // 1 if $b is before $a

if ($a < $b) { ... }                 // DateTime objects can be compared directly

Looping over dates

$period = new DatePeriod(
    new DateTimeImmutable('2026-11-01'),
    new DateInterval('P1D'),
    new DateTimeImmutable('2026-11-08')   // end is excluded
);
foreach ($period as $day) {
    echo $day->format('D d.m.'), PHP_EOL;
}

Previous: PHP Math and Number Functions · Next: PHP Files and Directories

Put together with AI as a quick reference I keep for my own work. Entries like this are usually not reviewed in detail by a person.