PHP Reference ยท Date and Time
Comparing and diffing dates in PHP
Reference for comparing dates in PHP: comparison operators on DateTime, diff() and DateInterval, days versus y/m/d parts, modify() and common DST pitfalls.
PHP date objects (DateTime and DateTimeImmutable) can be compared with the ordinary operators <, >, == and <=>. The comparison looks at the moment in time, so two objects in different time zones that represent the same instant are equal. To measure how far apart two dates are, call diff(), which returns a DateInterval.
You can also move a date by a relative amount with modify(), add() and sub(). Together these four tools cover most "how long until", "is it expired" and "next Monday" questions.
$a = new DateTimeImmutable('2024-01-31'); $b = new DateTimeImmutable('2024-03-01'); var_dump($a < $b); // bool(true) echo $a->diff($b)->days; // 30
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
public DateTimeInterface::diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval public DateTime::modify(string $modifier): DateTime|false public DateTimeImmutable::modify(string $modifier): DateTimeImmutable|false
| Name | Description |
|---|---|
$targetObject |
The date to compare against. The result describes the change from the object you call it on to this target. |
$absolute |
When true, the interval is always positive and invert stays 0. |
$modifier |
A relative date string such as +1 day, next friday or last day of next month. |
Return value: diff() returns a DateInterval with y, m, d, h, i, s, f, invert (1 if the target is earlier) and days (the total number of whole days). modify() returns the modified object, or false on a string it cannot parse (PHP 8.3 raises a warning and PHP 8.4 throws DateMalformedStringException).
Usage notes
- Use
daysfor totals anddfor the remainder.$diff->dis only the day part after years and months are removed, so it can never exceed 30.$diff->daysis the total span. invertcarries the sign. The numeric properties are always positive; checkinvert(or useformat('%R')) to know the direction.- Compare objects, not strings.
'2024-9-1' < '2024-10-01'compares text. Compare timestamps or date objects instead, or use ISO strings where text order equals time order. ==compares instants. Different zones are fine.===on objects tests identity, so two equal-valued objects are not===.- Month arithmetic overflows.
Jan 31 +1 monthbecomes March 2 in 2024 (March 3 in a non-leap year) because February has no 31st. Uselast day of next monthwhen you need the end of the month. - Daylight saving.
+1 daykeeps the wall-clock time, so a day can be 23 or 25 hours long.+24 hoursadds exactly 86,400 seconds. Pick the one that matches your meaning. modify()mutatesDateTime. OnDateTimeit changes the object and returns it; onDateTimeImmutableit returns a new one and leaves the original alone. Forgetting to use the return value is the classic immutable bug.- Birthday and age:
$birth->diff(new DateTimeImmutable('today'))->ygives completed years. - Sorting:
<=>works insideusort()callbacks and withmax()andmin(). - Business logic such as skipping weekends needs a loop or
DatePeriod;diff()counts calendar time only.