Key points
DateTimeImmutable::diff()returns a full interval:daysfor the total,y,m,dfor completed years, months and days, andinvertfor the direction.- Dividing a timestamp difference by 86,400 goes wrong around clock changes, and counting calendar days means resetting times to midnight first.
- Business days are counted with
DatePeriodand a holiday list, and “+1 month” doesn’t land on month end unless you ask for it explicitly.
“How many days between these two dates?” feels like a one-liner — until a customer reports a subscription that expired a day early, a delivery estimate showing “0 days” when the parcel ships tomorrow, or an invoice dated 3 March instead of 28 February. On our projects, those discrepancies almost always trace back to the same three causes: counting in seconds, forgetting about times of day, or treating months as fixed lengths. Here are dependable approaches for the everyday cases, with tested code.
The right foundation: DateTimeImmutable and diff()
PHP’s built-in date extension covers all of this without a library. diff() compares two dates and returns a DateInterval holding both the overall count and the breakdown into years, months and days.
$start = new DateTimeImmutable('2026-03-15');
$end = new DateTimeImmutable('2026-11-27');
$gap = $start->diff($end);
echo $gap->days; // 257: total number of days
echo $gap->y, ' year(s), ', $gap->m, ' month(s), ', $gap->d, ' day(s)';
// 0 year(s), 8 month(s), 12 day(s)
echo $gap->format('%R%a days'); // +257 days
echo $gap->invert; // 0: $end is after $start
Two properties look alike and get mixed up constantly. $gap->d is the number of days left over after whole months (12 here), whereas $gap->days is the total number of days between the dates (257). For “N days left”, you always want days. Also, days is never negative: the direction lives in invert, which is 1 when the second date comes before the first.
We always reach for DateTimeImmutable rather than DateTime. With the mutable class, $date->modify('+1 day') changes the original object, so a date passed between two functions ends up shifting under your feet. The immutable version returns a new object on every operation, which wipes out a whole family of bugs.
The 86,400-second trap and forgotten times of day
The habit inherited from older code is to subtract two timestamps and divide by 86,400, the number of seconds in a day. Except that not every day lasts 24 hours in a timezone with daylight saving.
date_default_timezone_set('Europe/London');
// Clocks go forward on Sunday 29 March 2026
$days = (strtotime('2026-03-30') - strtotime('2026-03-29')) / 86400;
var_dump($days); // float(0.958...): that day lasted 23 hours
$a = new DateTimeImmutable('2026-03-29');
$b = new DateTimeImmutable('2026-03-30');
var_dump($a->diff($b)->days); // int(1)
// With times: compare calendar days, not durations
$shipped = new DateTimeImmutable('2026-11-26 23:00');
$delivered = new DateTimeImmutable('2026-11-27 01:00');
$shipped->diff($delivered)->days; // 0 (2 hours apart)
$shipped->setTime(0, 0)->diff($delivered->setTime(0, 0))->days; // 1 calendar day
That 0.958 gets rounded down to 0 by floor() or an integer cast, and the bug only shows up two nights a year — exactly the kind you never reproduce in testing. diff() works in calendar terms and gets it right.
The second example is even more common: when dates carry a time, days counts complete 24-hour periods. Between 11 pm and 1 am there are 0 days, even though the date changed. If your business rule talks about calendar days (“delivered next day”, “follow up after 3 days”), reset both dates to midnight with setTime(0, 0) first.
Then there’s the timezone. A date created without one uses the server’s, which may not match your users’. Set it explicitly (new DateTimeImmutable('now', new DateTimeZone('Europe/London'))); in WordPress, wp_timezone() and current_datetime() return the timezone and current time configured in the site settings. Our rule of thumb: store in UTC, convert to the user’s timezone when calculating and displaying.
Age, time remaining and adding months
Age is a case where the interval breakdown is exactly what you need: y gives the number of completed years, accounting for whether the birthday has passed yet this year.
function age(string $birthDate, ?DateTimeImmutable $reference = null): int
{
$reference ??= new DateTimeImmutable('today');
return (new DateTimeImmutable($birthDate))->diff($reference)->y;
}
echo age('1990-06-15', new DateTimeImmutable('2026-11-27')); // 36
// "X days left" or "overdue"
$today = new DateTimeImmutable('today');
$left = $today->diff(new DateTimeImmutable('2026-12-15'));
echo $left->invert
? "Overdue by {$left->days} day(s)"
: "{$left->days} day(s) left";
// The month trap
$d = new DateTimeImmutable('2026-01-31');
echo $d->modify('+1 month')->format('Y-m-d'); // 2026-03-03 !
echo $d->modify('last day of next month')->format('Y-m-d'); // 2026-02-28
Passing the reference date as a parameter isn’t a detail: it’s what makes the function testable. A function that calls new DateTimeImmutable() internally returns something different every day, and its tests eventually fail on someone’s birthday.
The last example catches everyone out. “+1 month” bumps the month number, producing a non-existent 31 February that PHP rolls over into the following days: 3 March. For a monthly due date, billing or a renewal, use last day of next month to target month end, or keep the original anchor day (the 31st) and compute each due date from it, capping with min() against the number of days in the month (format('t')). Recomputing each month from the previous due date makes the date drift: after one pass through February, the customer gets billed on the 28th forever.
Counting business days
For processing times, delivery estimates or notice periods, you usually want business days: no weekends, no public holidays. DatePeriod makes it easy to walk through each day in the range. Here’s the version we use, with Easter-based holidays computed and fixed ones coming from configuration:
function easterHolidays(int $year): array
{
// easter_days() comes from the calendar extension (enabled on most hosts)
$easter = (new DateTimeImmutable("$year-03-21"))->modify('+' . easter_days($year) . ' days');
return [
$easter->modify('-2 days')->format('Y-m-d'), // Good Friday
$easter->modify('+1 day')->format('Y-m-d'), // Easter Monday
];
}
function businessDays(DateTimeImmutable $start, DateTimeImmutable $end, array $holidays = []): int
{
// +1 day: the end date is included
$period = new DatePeriod($start, new DateInterval('P1D'), $end->modify('+1 day'));
$count = 0;
foreach ($period as $day) {
if ($day->format('N') >= 6) { // 6 = Saturday, 7 = Sunday
continue;
}
if (in_array($day->format('Y-m-d'), $holidays, true)) {
continue;
}
$count++;
}
return $count;
}
// Fixed dates from your config, moveable ones computed
$holidays = array_merge(['2026-01-01', '2026-12-25'], easterHolidays(2026));
echo businessDays(new DateTimeImmutable('2026-04-01'), new DateTimeImmutable('2026-04-30'), $holidays);
// 20 (22 weekdays, minus Good Friday and Easter Monday)
Three lessons from practice. First, decide explicitly whether the bounds are included: here the end date is, hence the +1 day. Second, if the range spans two years, merge both years’ holidays. Third, in an application used across countries or regions — holiday calendars differ even within the UK — keep the list in configuration rather than in code.
Looping day by day is plenty fast for ranges of a few months. For thousands of calculations across several years, precompute a business-day table or use a calendar table in the database. And to filter a long list (“contracts expiring this month”), let MySQL compare dates in the query instead of loading every row into PHP.
FAQ
Why does diff() return 0 days when the dates are different?
Because both dates include a time and are less than 24 hours apart. days counts complete days. Reset both to midnight with setTime(0, 0) if you want calendar days.
How do I get a negative number of days when the date has passed?
days is always positive: multiply it by -1 when invert is 1, or use $interval->format('%r%a'), which adds a minus sign only when the interval is negative.
Deadline, due-date or subscription calculations that are occasionally off by a day? We audit and harden the business logic in your PHP applications, with tests that cover the calendar’s edge cases.



