PHP › Date & Time Handling

How do you calculate the difference between two dates in PHP, and what information does the DateInterval object returned by the diff method provide?

Intermediate

Answer

The diff method available on a DateTime object calculates the difference between that date and another given date, returning a DateInterval object containing properties representing the difference broken down into years, months, days, hours, minutes, and seconds, along with a total number of days, letting you easily express things like exactly how much time has passed since a specific event occurred.
$start = new DateTime('2026-01-01');
$end = new DateTime('2026-09-07');
$diff = $start->diff($end);
echo $diff->days . ' days';
Real-world example A membership platform calculates exactly how many days a user has been a member by finding the difference between their signup date and the current date, displaying that number prominently on their profile page.

Common follow-ups: What is the difference between the days property and manually calculating years, months, and days separately from a DateInterval?;How do you determine if one date comes before or after another date?