deftcode
Polski
← Back to blog

PHP in a nutshell: Dates and time

Read this in Polish
phpphp coursedates

What this part is about

Dates are an area where PHP has two parallel APIs:

  • the old, procedural one, built on Unix timestamps (the number of seconds elapsed since 01.01.1970 UTC);
  • the new, object-oriented one, introduced in version 5.2.

Both can do the same things — format a date, work out the difference between two of them, add a week — which is why every new project can, and in fact should, be built on the new API alone.

This part argues why the new API is the better choice (specifically its immutable variant), and shows the pitfalls that eat the most time when debugging date-related code.


Time zone first

Every formatting and every parsing of a date where you do not pass a zone explicitly happens relative to the default time zone of the PHP process. There is one per process, and it is worth setting deliberately — either in the configuration or in your bootstrap code:

; php.ini — date.timezone is a configuration directive, not a function
date.timezone = "Europe/Warsaw"
date_default_timezone_set('Europe/Warsaw'); // the same thing from code

If you do not set it anywhere, PHP defaults to UTC.

Isn’t UTC the recommended time zone for backend applications? It is — in two places: in the database and in the code that computes with those dates. The presentation layer is a separate matter, because a date usually reaches the user in their own zone. Conversion is therefore unavoidable; the trick is to make it happen in exactly two places — on the way in and on the way out.

Let’s follow the full journey of such a date: from the user, through the database, and back to the user.

date_default_timezone_set('UTC'); // the whole application computes in UTC
$userZone = new DateTimeZone('Europe/Warsaw'); // zone taken from the user's profile
// 1. input — the user gives a date in their own zone, so we pass it explicitly
$input = new DateTimeImmutable('2026-01-02 00:30', $userZone);
$input->format('Y-m-d H:i P'); // 2026-01-02 00:30 +01:00
// 2. writing to the database — conversion to UTC
$toDatabase = $input->setTimezone(new DateTimeZone('UTC'));
$toDatabase->format('Y-m-d H:i:s'); // 2026-01-01 23:30:00 ← A DIFFERENT DAY than the user's
// 3. reading — the database holds a bare value with no zone, so again we pass it explicitly
$fromDb = new DateTimeImmutable('2026-01-01 23:30:00', new DateTimeZone('UTC'));
// 4. display — conversion to the user's zone
$fromDb->setTimezone($userZone)->format('Y-m-d H:i'); // 2026-01-02 00:30 ← what they typed

Step 2 is the important one: adding a time zone can change the value of the day. The same instant has the date 2026-01-01 in UTC and 2026-01-02 for the user. Skipping either of these conversions therefore does not end with an hour’s shift, but with a date from a different day — and such a date looks perfectly fine, so nobody questions it:

date_default_timezone_set('Europe/Warsaw'); // a default zone other than UTC
// the zone omitted in step 3 — PHP takes the default and reads the stored value as Warsaw time
$fromDb = new DateTimeImmutable('2026-01-01 23:30:00');
$fromDb->setTimezone($userZone)->format('Y-m-d H:i'); // 2026-01-01 23:30 — hour and day both wrong

How do we know which zone the client is in

Ideally we should not have to know. The rule is to accept an unambiguous instant on the way in — a date that makes it clear which moment is meant, with no guessing. In practice that means ISO 8601 notation with an offset, that is a shift relative to UTC written as a value: +01:00, -05:00, +00:00.

An offset is not the same thing as a time zone, even though in everyday speech the two words get used interchangeably:

  • +01:00 says only how much this one hour differs from UTC;
  • Europe/Warsaw is a name from the IANA database and a whole set of rules, including the dates on which the clocks change.

One zone can therefore have two different offsets over the course of a year:

$warsaw = new DateTimeZone('Europe/Warsaw');
(new DateTimeImmutable('2026-01-15 12:00', $warsaw))->format('P'); // +01:00 — winter time
(new DateTimeImmutable('2026-07-15 12:00', $warsaw))->format('P'); // +02:00 — summer time

The practical conclusion: wherever you store a zone permanently — in the application’s configuration, in a user profile, in a database column — store the zone name, not the offset. An offset frozen in such a place stays true only until the next clock change:

// the same wall-clock hour, once with a hard-coded offset, once with a zone
new DateTimeImmutable('2026-07-15 12:00', new DateTimeZone('+01:00')); // = 11:00 UTC
new DateTimeImmutable('2026-07-15 12:00', $warsaw); // = 10:00 UTC

In July, Warsaw is on +02:00, so the offset +01:00 points at a moment an hour earlier than the user had in mind.

What the offset in a transmitted date actually says

It says exactly one thing — and nothing more. A client application sending 2026-07-15T12:00:00+02:00 is not declaring “I live in the +02:00 zone”. It is saying: “my 12:00 is the same instant as 10:00 in UTC”.

And that is entirely enough for the backend to know which instant is meant: from that value alone you can work out the moment in UTC without ambiguity — that is, in the time zone we use when writing the value to the database.

You can see this in the fact that the result does not depend on the zone the backend happens to run in:

$sent = '2026-07-15T12:00:00+02:00'; // what the client sent
$utc = new DateTimeZone('UTC');
date_default_timezone_set('UTC');
(new DateTimeImmutable($sent))->setTimezone($utc)->format('Y-m-d H:i:s'); // 2026-07-15 10:00:00
date_default_timezone_set('America/New_York');
(new DateTimeImmutable($sent))->setTimezone($utc)->format('Y-m-d H:i:s'); // 2026-07-15 10:00:00 — the same

The instant is therefore decided by the offset in the transmitted value, not by the server’s configuration.

An offset is not enough, however, wherever you need more than one given instant — that is, when you have to reproduce the user’s local time on a different day.

When an offset, and when a zone name

One question decides it: are you storing an event or a rule?

What you store Example What is enough
an event that already happened created_at, a log entry, an order date the instant — an offset on input
a deadline counted in absolute time a token expires in an hour, a 48 h SLA the instant — an offset on input
a future meeting or reminder agreed in local time “15.01.2027 at 9:00 my time” local time plus a zone name
a recurring rule “every day at 9:00”, “on the 1st of the month” a zone name
a user preference which zone to display dates in a zone name

The first two rows are events: the instant is already settled, so the offset in the transmitted value does the job. The next three are rules — they are meant to hold in the future, and a future offset is not known, because it depends on clock changes and sometimes simply on a legislator’s decision.

Take a typical case: a reminder set a few months ahead. That is the third row of the table, so the answer is: local time together with a zone name, not an offset. Here is what happens if you compute UTC using the offset current at the moment the reminder is set:

$warsaw = new DateTimeZone('Europe/Warsaw');
$utc = new DateTimeZone('UTC');
// today is 3 October 2026, Warsaw is on +02:00
// the user: remind me on 15.01.2027 at 9:00 my time
// WRONG — the offset taken from today, frozen into the stored value
$naive = new DateTimeImmutable('2027-01-15 09:00', new DateTimeZone('+02:00'));
$naive->setTimezone($utc)->format('H:i'); // 07:00 — this is what goes to the database
$naive->setTimezone($warsaw)->format('H:i'); // 08:00 — and this is when it will ring (!)
// RIGHT — a zone name, with the offset worked out for the target day
$good = new DateTimeImmutable('2027-01-15 09:00', $warsaw);
$good->setTimezone($utc)->format('H:i'); // 08:00
$good->setTimezone($warsaw)->format('H:i'); // 09:00 — as agreed

In January, Warsaw is on +01:00, not +02:00 — the offset remembered in October is untrue for that date, and the reminder rings an hour early.

In the database this means two columns instead of one: the local time (2027-01-15 09:00:00) and the zone name (Europe/Warsaw). This is not something made up for this article — it is exactly what the iCalendar standard (RFC 5545) does, storing an event’s date as local time with a TZID parameter, and calendar APIs return dates in the same form.

Hence the whole split: an offset for transmitting one specific instant, a zone name for everything that is meant to hold in the future as well.

In code it looks like this:

date_default_timezone_set('UTC'); // the process default zone
new DateTimeImmutable('2026-01-02T00:30:00+01:00'); // 2026-01-01 23:30 UTC — the offset taken
// from the date's text value, here +01:00
new DateTimeImmutable('2026-01-01T23:30:00Z'); // 2026-01-01 23:30 UTC — 'Z' is the ISO 8601
// shorthand for the +00:00 offset, i.e. UTC itself
// (from the military "Zulu"); equivalent to
// ...23:30:00+00:00
new DateTimeImmutable('2026-01-02 00:30:00'); // 2026-01-02 00:30 UTC — this value carries no
// offset and no zone, so PHP took the default.
// And this is where bugs come from.

The first two forms are unambiguous, and they are the ones worth insisting on in an API contract — then validating that a date value really does arrive with an offset. The same goes for what your API returns.

Hence the rule of thumb: if the exact hour matters to you, require the offset to be sent.


The old procedural API

In the old API a date is a Unix timestamp, that is an int. The API itself consists mainly of functions that produce such an int or turn it into human-readable text:

time(); // 1790937701 — the current timestamp, always in UTC
date('Y-m-d H:i:s'); // '2026-10-02 12:43:38' — a timestamp formatted in the default zone
mktime(1, 2, 3, 12, 31, 2026); // 1798671723 — a timestamp from its parts: hour, minute, second,
// month, day, year (yes, in that order)
checkdate(2, 30, 2026); // false — whether such a date exists in the calendar (it handles leap
// years: checkdate(2, 29, 2028) is true)

Two things in the code above are worth remembering:

  • mktime() has an unusual argument order — the time comes before the date, and within the date the month comes before the day. This is a classic source of mistakes.
  • checkdate() operates on numbers rather than on a text value, which is worth keeping in mind.

Why learn this if the object API does the same

For two specific reasons — fortunately neither of them is critical.

First, you may come across this approach in old code, and it helps to at least recognise what you are looking at. Second, checkdate() has no object-oriented counterpart, and it is the simplest way to reject a date that does not exist in the calendar — the object route silently rolls such a date over into the next month, which we will get to in the section on parsing.

Timestamps themselves also turn up outside these functions: you get them from filemtime(), from $_SERVER['REQUEST_TIME'], from the exp claim in a JWT or from a cache TTL. That does not mean you have to rely on them, though — the newer API has its own ways of parsing a numeric timestamp.

strtotime()

strtotime() takes a date described in English and returns a Unix timestamp. The description can be a specific date, but it can also be a relative expression — counted from “now” or from a reference point given in the second argument:

strtotime('2026-08-29'); // 1787954400 — a specific date
strtotime('+1 week 2 days'); // a shift relative to now
strtotime('tomorrow'); // the next midnight
strtotime('first day of february');
strtotime('last day of february'); // handles leap years
strtotime('second friday of january');
strtotime('+1 day', $timestamp); // the second argument is the reference point

strtotime() returns false when it does not understand the description — and false in a loose comparison behaves like 0, that is 1 January 1970. Always check the result with === false, just as we discussed with falsy values.

Format characters

The date() function takes a format — a string in which every letter stands for one field of the date, while everything that is not a letter with an assigned meaning goes into the result unchanged. The same table applies throughout PHP, so we will come back to it with the object API. In the pairs below, the variant to the left of the slash is the one with a leading zero, and to the right the one without.

Char Meaning Char Meaning
Y / y 2026 / 26 H / G 00–23 / 0–23
m / n 01–12 / 1–12 h / g 01–12 / 1–12
d / j 01–31 / 1–31 i / s minutes / seconds
D / l Mon / Monday A / a AM / am
M / F Jan / January N / w ISO weekday 1–7 / 0–6
L leap year 1/0 t number of days in the month
U timestamp T / e / P zone abbreviation / identifier / +02:00
c ISO 8601 r RFC 2822

If one of those letters is to appear in the result literally, precede it with a backslash (\). This is most often needed for the letter T in ISO 8601 notation, because without escaping T means the zone abbreviation:

$ts = mktime(14, 30, 0, 8, 29, 2026); // 29 August 2026, 14:30
date('Y-m-d\TH:i:sP', $ts); // '2026-08-29T14:30:00+02:00' — this is what you want
date('Y-m-dTH:i:sP', $ts); // '2026-08-29CEST14:30:00+02:00' — T substituted the zone abbreviation

Dates in other languages

The text value of a date produced by date() is always in English — regardless of the time zone setting or of any use of setlocale(). This applies to the names of days and months, that is the letters D, l, M and F. To get the result in another language, use IntlDateFormatter from the intl extension:

date('l, j F Y', $ts); // 'Saturday, 29 August 2026' — date() speaks English only
$cs = new IntlDateFormatter(
'cs_CZ',
IntlDateFormatter::FULL, // date style: FULL, LONG, MEDIUM, SHORT or NONE
IntlDateFormatter::NONE, // time style — here we skip the time
'Europe/Prague',
);
$cs->format($ts); // 'sobota 29. srpna 2026'

As you can see above, IntlDateFormatter does not take a format letter by letter; it picks from ready-made styles of date and time: FULL, LONG, MEDIUM, SHORT or NONE. If none of them suits us, we can define our own pattern and pass it as the sixth constructor argument. It uses ICU letters — the set defined by the ICU library that intl relies on underneath. These are an entirely different set from the date() ones, and the only place in PHP where you will run into them. Usually we need just a few, as the example below shows:

Pattern Meaning Result for 29.08.2026, 14:30
y / yy year 2026 / 26
MM / MMM / MMMM month as a number / abbreviation / name 08 / srp / srpna
LLLL standalone month name srpen
d / dd day without / with a leading zero 29 / 29
E / EEEE day of the week so / sobota
HH / mm / ss hour / minutes / seconds 14 / 30 / 00
$own = new IntlDateFormatter('cs_CZ', IntlDateFormatter::NONE, IntlDateFormatter::NONE,
'Europe/Prague', null, 'LLLL y');
$own->format($ts); // 'srpen 2026'

Note the difference between MMMM and LLLL, which matters in languages with grammatical cases — in Czech, MMMM gives the genitive form (“29. srpna 2026”) and LLLL the nominative for standalone use (“srpen 2026”). In English the two are identical, which is exactly why the distinction is easy to miss until a translation is wrong. The full list of letters is in the ICU documentation.

One small detail that will come in handy later: IntlDateFormatter::format() accepts both a timestamp and a date object, so you will use the same class with either approach.


The object API

The newer approach represents dates as objects rather than numeric values, and it is today’s default choice. It consists of four classes, which will show up over the rest of this article:

  • DateTimeImmutable and DateTime — an instant: a specific date with a time and a zone;
  • DateTimeZone — a time zone, passed as an object rather than a string;
  • DateInterval — an amount of time not tied to any specific date: “three days”, “a year and a half”;
  • DatePeriod — a sequence of dates produced by shifting a starting point by an interval.

The gain over timestamps is twofold. First: an instant carries its time zone with it, so you do not have to remember which zone it is expressed in. Second: if a function signature says it takes or returns DateTimeImmutable, we know we are dealing with a date — whereas time() gives us an int, indistinguishable from any other number.

DateTime versus DateTimeImmutable

There are two classes to choose from for creating objects that represent dates. Choosing between them is the most important decision in this whole part, so let me give you the right answer straight away: use DateTimeImmutable by default.

Both have an identical interface. They differ in one thing — what the methods that modify the date value in any way actually do:

$a = new DateTime('2026-01-01');
$b = $a->modify('+1 month');
$a->format('Y-m-d'); // 2026-02-01 — $a changed as well (!)
$b->format('Y-m-d'); // 2026-02-01
$a === $b; // true
$a = new DateTimeImmutable('2026-01-01');
$b = $a->modify('+1 month');
$a->format('Y-m-d'); // 2026-01-01 — $a untouched
$b->format('Y-m-d'); // 2026-02-01
$a === $b; // false

The two snippets are identical — the same date, the same modify('+1 month'), the same assignment to $b. Only the class name differs, and yet $a ends up with two different values. The answer is in the last line, the $a === $b comparison, which checks whether both variables point at the same object:

  • DateTime::modify() changes the object in place and returns $this, which is still $a. The assignment $b = $a->modify(…) therefore creates nothing new — it just makes a second name for the same, already modified date. Hence true and two identical values.
  • DateTimeImmutable::modify() leaves $a alone and returns a brand-new object with the computed date. $a and $b are two separate objects, each with its own value. Hence false.

Why assignment on its own does not protect the original is something we covered with references: assigning an object copies the object identifier, not the object itself.

Diagram: assigning a DateTime object copies the object identifier, so modify changes the object seen through both variables, while DateTimeImmutable returns a new object and leaves the original untouched
DateTime::modify() changes the object in place. DateTimeImmutable::modify() returns a new one and leaves the original alone.

The innocent-looking code below could make life considerably harder. Let’s look at an example function that takes a date as an argument and wants to work out how many days are left until the end of the month:

function daysUntilEndOfMonth(DateTime $date): int
{
$endOfMonth = $date->modify('last day of this month');
return (int) $date->diff($endOfMonth)->days;
}
$order = new DateTime('2026-01-10');
daysUntilEndOfMonth($order); // 0 — and it should be 21
$order->format('Y-m-d'); // 2026-01-31 — the order date has been moved (!)

One line, two casualties. modify() changed $date in place and returned the same object, so $endOfMonth and $date are two names for one date — which leads to diff() computing the difference between two identical dates, giving 0. On top of that, the function has corrupted the order date for whoever called it, even though all it was supposed to do was compute something.

Changing the type to DateTimeImmutable is enough for the same function to return 21 and leave $order at 2026-01-10. With the immutable class such a bug is impossible: every modification produces a new object, and if you forget to assign the result, you will not see the effect of your operation anywhere.

Creating and modifying

The constructor takes a date as a string (the same set of expressions as strtotime()) and optionally a zone. You read the value with format() or getTimestamp():

$created = new DateTimeImmutable('2026-08-29 14:30', new DateTimeZone('Europe/Warsaw'));
$created->format('Y-m-d H:i'); // '2026-08-29 14:30'
$created->getTimestamp(); // 1788006600

The modifying methods do not change $created; they return a new object with the modified date. This lets you derive any number of other dates from one, each a separate value under its own name:

$payUntil = $created->add(new DateInterval('P14D')); // 2026-09-12 14:30 — payment deadline
$reminder = $payUntil->sub(new DateInterval('P2D')); // 2026-09-10 14:30 — reminder
$endOfMonth = $created->modify('last day of this month'); // 2026-08-31 14:30
$startOfDay = $created->setTime(0, 0); // 2026-08-29 00:00 — seconds zeroed too
$otherDay = $created->setDate(2027, 1, 15); // 2027-01-15 14:30 — time untouched
$sameInUtc = $created->setTimezone(new DateTimeZone('UTC')); // 2026-08-29 12:30 — the same instant
$created->format('Y-m-d H:i'); // '2026-08-29 14:30' — none of those lines touched it

None of these lines changes the object it works on — $created looks exactly the same afterwards as before, and $payUntil survives the computation of $reminder. Their order therefore does not matter, and none of them spoils the result of the others. This is precisely why we use DateTimeImmutable: such a date can safely be passed on, or have several others derived from it, without any worry that someone along the way will quietly change its value.

setTimezone() does not change the instant, only the way it is presented. You can see this on $sameInUtc: it shows 12:30 and $created shows 14:30, but both describe the same instant — getTimestamp() returns an identical number for them.

If the intermediate steps are of no use to you, the methods can be chained. Each one returns an object, so the next has something to work on:

$deadline = $created
->modify('last day of this month')
->setTime(23, 59)
->add(new DateInterval('P1D'));
$deadline->format('Y-m-d H:i'); // 2026-09-01 23:59
$created->format('Y-m-d H:i'); // 2026-08-29 14:30 — the original still untouched

Creating dates from a timestamp and from relative expressions

Here we come back to two things from the section on the old API — because both are available on the object side as well, and this is where you actually use them.

The first is the timestamp, that is a Unix timestamp in the form of a numeric value (int). You stand a good chance of meeting such a value in many places in the language — for instance it is returned by the filemtime() function, which gives a file’s last modification time. You turn it into an object with one of three forms:

$ts = 1790937701;
$now = new DateTimeImmutable();
DateTimeImmutable::createFromTimestamp($ts); // PHP 8.4 — the clearest one
new DateTimeImmutable("@$ts"); // the older form: '@' before the timestamp
$now->setTimestamp($ts); // on an existing object

There is a difference in zone between them that is worth remembering: createFromTimestamp() and the @ form give an object in UTC, regardless of the default zone — because the timestamp itself is in UTC and brings nothing else with it. setTimestamp(), on the other hand, keeps the zone the object already had.

The other way round there is getTimestamp(), and here the zone makes no difference at all: the same instant returns the same number, regardless of the zone it is displayed in.

$warsaw = new DateTimeImmutable('2026-08-29 14:30', new DateTimeZone('Europe/Warsaw'));
$tokyo = $warsaw->setTimezone(new DateTimeZone('Asia/Tokyo'));
$warsaw->format('H:i'); // 14:30
$tokyo->format('H:i'); // 21:30 — a different hour on the clock
$warsaw->getTimestamp(); // 1788006600
$tokyo->getTimestamp(); // 1788006600 — the same number, because it is the same instant

The second thing we met with the old API is the language of relative expressions — the one behind second friday of january. It is not tied to strtotime(): modify() accepts exactly the same values, because the same parser runs underneath. The only difference is what you get back — an object instead of an int:

$d = new DateTimeImmutable('2026-01-15');
$d->modify('second friday of january')->format('Y-m-d'); // 2026-01-09
$d->modify('last day of february')->format('Y-m-d'); // 2026-02-28

So: the syntax is worth knowing, but you do not have to go back to the old API for it. The error behaviour here is better too — modify() does not return false; since PHP 8.3 it throws a DateMalformedStringException, just like the constructor:

strtotime('utterly not a date'); // false — silently
$d = new DateTimeImmutable('2026-01-01');
$d->modify('utterly not a date');
// DateMalformedStringException: Failed to parse time string (utterly not a date) at position 0

A description that was not understood is therefore impossible to miss: instead of a false that travels halfway across the application and ends up as 1 January 1970, you get an exception right where the problem actually arose.


Parsing a date of known format

A date in text form can be parsed in two ways.

The first is to pass such a value to the DateTimeImmutable constructor — or to strtotime(), which uses the same parser:

new DateTimeImmutable('2026-05-12'); // 2026-05-12
new DateTimeImmutable('12.05.2026'); // 2026-05-12
new DateTimeImmutable('May 12, 2026'); // 2026-05-12
new DateTimeImmutable('12 May 2026'); // 2026-05-12

This approach copes quite well with the usual ways of presenting dates as text, but it only works when we are dealing with a value we know in advance to be a valid date in a predictable notation — that is, with data we control. With a value coming from a user or from an external system there is a risk that PHP will read those digits differently from what we mean. We will come back to this with separators.

The second way is createFromFormat(), which we tell explicitly what format to expect the date in — in the same notation as in date():

$d = DateTimeImmutable::createFromFormat('d/m/Y', '29/08/2026');
DateTimeImmutable::getLastErrors(); // returns what errors and warnings occurred during the last
// parse — or false when there were none

Three pitfalls await us here — we will say more about each of them below — and all three can slip unnoticed into production.

A missing time is filled in with the current one

new DateTimeImmutable('2026-05-12');
// 2026-05-12 00:00:00 — the missing time is midnight
DateTimeImmutable::createFromFormat('d/m/Y', '12/05/2026');
// 2026-05-12 14:37:52 — the missing time is the CURRENT hour (!)

Passing the same date in two different ways can therefore give a different value underneath, and comparing those dates will return false. The sneaky part is that once printed through format('Y-m-d') both look identical — 2026-05-12 — so looking at them you will not see any difference.

There are two solutions:

DateTimeImmutable::createFromFormat('d/m/Y H:i:s', '12/05/2026 00:00:00'); // the time stated explicitly
DateTimeImmutable::createFromFormat('d/m/Y|', '12/05/2026'); // '|' zeroes the rest
DateTimeImmutable::createFromFormat('!d/m/Y', '12/05/2026'); // '!' at the start does the same

The | character means “set every field I did not list to zero”; ! at the start of the format works identically. Both are shorter and harder to forget than always writing the time out explicitly.

A non-existent date is not an error

This is the most treacherous of the three, because createFromFormat() returns false only when the string does not match the format. A date that does match the format but does not exist in the calendar is not an error — PHP rolls the excess over into the next month:

DateTimeImmutable::createFromFormat('Y-m-d', 'abc'); // false — does not match the format
DateTimeImmutable::createFromFormat('Y-m-d', '2026-02-30'); // an object (!) — the date 2026-03-02
new DateTimeImmutable('2026-02-30'); // the same — 2026-03-02

30 February does not exist, but that does not cause an error. The only trace of it is in getLastErrors(), and as a warning rather than an error — so checking error_count gets you nowhere:

DateTimeImmutable::getLastErrors();
// ['warning_count' => 1, 'warnings' => [10 => 'The parsed date was invalid'],
// 'error_count' => 0, 'errors' => []]

If you are validating a date that comes from a user, you have two options. The first is checkdate() on the separate numbers — and this is the case where the old API wins on simplicity. The second is to check whether the formatted result is identical to the input:

function isValidDate(string $input): bool
{
$d = DateTimeImmutable::createFromFormat('!Y-m-d', $input);
return $d !== false && $d->format('Y-m-d') === $input;
}
isValidDate('2026-02-30'); // false — it rolled over to 2026-03-02, so it no longer matches the input
isValidDate('2026-02-28'); // true
isValidDate('2028-02-29'); // true — a leap year

The separator decides the interpretation

When parsing without an explicit format (new DateTimeImmutable(…), strtotime()), the order of the fields is decided by the separating character:

Notation Interpretation Result
12/05/2026 slashes → American m/d/Y 5 December
12-05-2026 dashes → European d-m-Y 12 May
12.05.2026 dots → European d.m.Y 12 May

The same digits, three different separators, two different dates. If you are parsing anything that comes from a user or from an external system, always state the format explicitly with createFromFormat().


Differences between dates

To work out how much time has passed between two dates, you call diff() on one of them and pass it the other. The result is not a number but a DateInterval object — the same type that describes a stretch of time when adding and subtracting:

$diff = $start->diff($end); // returns a DateInterval
$diff->days; // the TOTAL number of days — set only by diff()
$diff->y; // component: years
$diff->m; // component: months
$diff->d; // component: days
$diff->invert; // 1 when the difference is negative
$diff->format('%a days, %h hours');

The distinction between days and d is a source of bugs: days is the total length of the difference, while y, m and d are its breakdown into components. For a difference of a year and two days, days gives 367 and d gives 2.

And let me head off a question here, because the name days suggests there are more such properties: there are not. days is the only total value DateInterval exposes — there is no years, no months and no weeks. The whole list is short: y, m, d, h, i, s, f (microseconds), invert and days. If you need the total number of weeks or hours, you work it out yourself from days.

intdiv($diff->days, 7); // the total number of whole weeks

The second thing: days only makes sense for an interval returned by diff(). An interval you created yourself does not know which dates it lies between, so it has nothing to compute the total length from:

(new DateInterval('P1M2D'))->days; // false — not from diff(), so no total number of days

Formatting an interval

DateInterval has its own format(), and it uses a separate set of characters — not the date() ones. Each starts with a percent sign; a lowercase letter gives the value without a leading zero, an uppercase one with:

Char Meaning Char Meaning
%y / %Y years: 1 / 01 %h / %H hours: 5 / 05
%m / %M months: 2 / 02 %i / %I minutes: 6 / 06
%d / %D days (component): 9 / 09 %s / %S seconds: 7 / 07
%a the TOTAL number of days %f / %F microseconds
%R always a sign: + or - %r a sign only for negatives
%% a literal percent sign
$diff = (new DateTimeImmutable('2026-01-01'))->diff(new DateTimeImmutable('2027-03-10 05:06:07'));
$diff->format('%y years, %m months, %d days'); // '1 years, 2 months, 9 days'
$diff->format('%a days in total'); // '433 days in total'
$diff->format('%R%a'); // '+433'

Mind the same trap as with the properties: %d is the component of days, while %a is the total. On an interval created by hand, %a returns the literal string (unknown).

format() will not handle inflection or plurals — it matches no grammatical number, which is why the example above comes out as “1 years”. For text shown to users you need MessageFormatter from intl or a ready-made library.


Intervals and ranges

DateInterval is an amount of time, not an instant: “two days”, “three months”, “half an hour”. On its own it knows nothing about the calendar — it turns into a concrete shift only once you apply it to a specific date through add(), sub() or DatePeriod. It comes in handy for storing a subscription length, an invoice payment term or the step in a loop over days.

You get one from two sources: from diff(), as in the section above, or you create it yourself. And creating your own interval is the one unintuitive thing about this class, because the constructor accepts neither numbers nor unit names.

The ISO 8601 specification

The DateInterval constructor takes a single argument: a string in the ISO 8601 duration format.

new DateInterval('P1M2DT3H'); // 1 month, 2 days, 3 hours

The notation looks cryptic, but three rules govern it. P opens the whole thing, T separates the date part from the time part, and every number is followed by a letter saying which unit it is given in:

P1Y2M3DT4H5M6S
│ │ │ ││ │ │ └── S — seconds
│ │ │ ││ │ └──── M — minutes (after T)
│ │ │ ││ └────── H — hours
│ │ │ │└──────── T — start of the time part
│ │ │ └───────── D — days
│ │ └─────────── M — months (before T)
│ └───────────── Y — years
└─────────────── P — start of the whole notation

The available letters are Y, M, W and D before T, and H, M and S after it. They are all optional, so you give only the ones you need — and no spaces are allowed in this notation. Note that M appears on both sides of T, and it is T that decides what a given M means. Before T it is months, after T it is minutes.

new DateInterval('P30M'); // 30 months
new DateInterval('PT30M'); // 30 minutes

If this format puts you off, there is a more readable way out — createFromDateString(), which takes a description in English, exactly like strtotime():

DateInterval::createFromDateString('1 month 2 days 3 hours'); // the same as 'P1M2DT3H'

Both forms are validated immediately — an invalid string ends with a DateMalformedIntervalStringException whichever you choose. The difference lies elsewhere: ISO 8601 is a standard, language-independent notation, so you will meet it in configuration files, in API responses and in other programming languages. createFromDateString() is a convenience of PHP’s own.

DatePeriod

DatePeriod is an iterator over dates: you give it a starting point, an interval and an end, and foreach walks through the successive dates produced by adding that interval. This lets you write a loop “over every day of the month” without working out by hand how many days that month has.

$period = new DatePeriod(
new DateTimeImmutable('2026-01-01'),
new DateInterval('P1D'),
new DateTimeImmutable('2026-02-01'), // THE END IS EXCLUSIVE
);
foreach ($period as $day) {
echo $day->format('Y-m-d'); // 2026-01-01 … 2026-01-31 — 31 dates, without 2026-02-01
}

The end date does not enter the range. If you need it included, add one more interval or give a number of recurrences instead of an end date:

$start = new DateTimeImmutable('2026-01-01');
new DatePeriod($start, new DateInterval('P1D'), 5);
// 6 dates: 01-01, 01-02, 01-03, 01-04, 01-05, 01-06 — the start plus 5 recurrences

The start date, on the other hand, does enter the range by default, but we can also decide to exclude it — the DatePeriod::EXCLUDE_START_DATE flag in the fourth argument is there for that:

$end = new DateTimeImmutable('2026-01-05');
new DatePeriod($start, new DateInterval('P1D'), $end);
// 4 dates: 01-01, 01-02, 01-03, 01-04
new DatePeriod($start, new DateInterval('P1D'), $end, DatePeriod::EXCLUDE_START_DATE);
// 3 dates: 01-02, 01-03, 01-04 — without the starting day

This asymmetry is worth remembering: the end is excluded from the range by default, while the start has to be excluded by hand.


When to reach for a library

The built-in API is enough for formatting, arithmetic and ranges. It becomes awkward for four things: descriptions such as “3 days ago”, handy shortcuts along the lines of “the first day of this month”, checks of the “is this date a weekend” variety, and testing code that depends on a specific date.

The last one matters most. A method that itself calls new DateTimeImmutable('now') inside is practically untestable — in a test you have no way of telling it what time it is. Every run gets a different date, so you cannot check what happens the day before a deadline, the day after it, or on 29 February.

There are two ways out, and both come down to the same thing: “now” should be something a method receives from outside, not something it helps itself to. The first is to pass it a clock object, which returns the real date in production and any date you like in a test; the standard for such a clock is the Psr\Clock\ClockInterface interface. The second is to reach for a library that can “freeze” time for the purposes of a test — this is how Carbon’s setTestNow() works, which we get to below.

The first approach is dependency injection, and we will come back to it in the parts on OOP.

Carbon

The most popular date library is nesbot/carbon, and it is often used in place of the native classes — especially in projects built on the Laravel framework, where it is used by default.

What it gives you is above all convenience. CarbonImmutable extends DateTimeImmutable, so everything the native classes can do Carbon can do too — and on top of that it adds several hundred helper methods, aimed at exactly the gaps listed above:

$d->diffForHumans(); // '3 days ago'
$d->startOfMonth(); // the first day of the month, 00:00
$d->isWeekend(); // bool
CarbonImmutable::setTestNow('2026-01-01 12:00'); // freezing "now" for the duration of a test

With this or any other library there is one thing to watch out for, though: its class starts to spread across method signatures throughout the project, tying you to it in the long term. That is why a common compromise is to keep DateTimeImmutable in the domain and use the library selectively — where it genuinely shortens the code.


What’s next

That was the last part about the procedural core. From the next one on we move into object-oriented programming and stay there until the end of the series.

Part seven: classes, properties and constructors with promoted parameters, visibility, readonly, static properties and methods, late static binding, inheritance and abstract classes, interfaces and traits — along with an answer to the question of when each of these tools is actually the right one.

Comments