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| Char | Meaning | Example |
|---|---|---|
Y / y | year 4 / 2 digits | 2026 / 26 |
m / n | month with / without zero | 03 / 3 |
d / j | day with / without zero | 05 / 5 |
H / G | hour 24h with / without zero | 09 / 9 |
h / A | hour 12h / AM or PM | 09 / PM |
i / s | minutes / seconds | 07 / 30 |
D / l | weekday short / full | Sun / Sunday |
M / F | month short / full | Nov / November |
N | weekday 1 (Mon) – 7 (Sun) | 7 |
W | ISO week number | 46 |
t | days in month | 30 |
U | timestamp | |
c | ISO 8601 | 2026-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');DateTimeImmutable (recommended)
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 directlyLooping 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.