Date and time
A publication date, the end of a discount, a user's age — no site does without dates. PHP has the simple date() function and more powerful objects.
The current date
The date() function returns the current date in a given format. The letters in the format string are replaced with parts of the date:
<?php
$today = date('d.m.Y');
echo strlen($today); // 10The result depends on the day you run it — 30.01.2025, for example.
Format letters
| Letter | Meaning | Example |
|---|---|---|
d | Day with a leading zero | 05 |
m | Month with a leading zero | 01 |
Y | Year | 2025 |
H | Hours, 24-hour format | 14 |
i | Minutes | 07 |
s | Seconds | 30 |
N | Day of the week, 1 is Monday | 4 |
A date object
For calculations the DateTimeImmutable object is handier. The constructor takes the date as a string:
<?php
$date = new DateTimeImmutable('2025-01-30 14:05');
echo $date->format('d.m.Y'), "\n"; // 30.01.2025
echo $date->format('H:i'); // 14:05Without an argument the object holds the current moment.
Adding and subtracting
The modify() method shifts the date and returns a new object:
<?php
$date = new DateTimeImmutable('2025-01-30');
echo $date->modify('+7 days')->format('d.m.Y'), "\n"; // 06.02.2025
echo $date->modify('-1 month')->format('d.m.Y'), "\n"; // 30.12.2024
echo $date->modify('last day of this month')->format('d.m.Y'); // 31.01.2025The original object does not change — that is what Immutable means.
The difference between dates
The diff() method returns the interval between two dates:
<?php
$start = new DateTimeImmutable('2025-01-01');
$finish = new DateTimeImmutable('2025-03-01');
$interval = $start->diff($finish);
echo $interval->days, "\n"; // 59
echo $interval->m; // 2The days property is the total number of days, m and d are months and days separately.
Comparing
Date objects are compared with the usual operators:
<?php
$deadline = new DateTimeImmutable('2025-06-01');
$now = new DateTimeImmutable('2025-05-20');
echo $now < $deadline ? 'There is still time' : 'The deadline has passed';A date from user input
createFromFormat() parses a date in a known format and returns false if the string does not fit:
<?php
$date = DateTimeImmutable::createFromFormat('d.m.Y', '30.01.2025');
echo $date ? $date->format('Y-m-d') : 'Invalid date'; // 2025-01-30Common mistake
PHP also has the DateTime class, and its methods change the object itself. A variable you thought of as the "start" changes silently:
<?php
$start = new DateTime('2025-01-30');
$finish = $start->modify('+1 day');
echo $start->format('d.m.Y'); // 31.01.2025 — the start changed tooUse DateTimeImmutable — it has no such surprises.