Question
I have two dates in this format:
$startDate = '2007-03-24';
$endDate = '2009-06-26';
I want to calculate the difference between them and display the result in a readable format like:
2 years, 3 months and 2 days
How can I do this in PHP?
Short Answer
By the end of this page, you will understand how to calculate the difference between two dates in PHP using DateTime and DateInterval. You will learn the correct syntax, how PHP breaks a date gap into years, months, and days, how to format the result, and how to avoid common mistakes such as treating dates as plain strings or manually calculating month lengths.
Concept
PHP provides built-in date tools that make date calculations much easier and safer than manual math. The main idea is:
- Convert date strings into
DateTimeobjects - Compare them using the
diff()method - Read the result from a
DateIntervalobject
This matters because dates are not simple numbers:
- Months have different lengths
- Leap years exist
- Time zones can affect calculations
- Manual subtraction often produces incorrect results
In PHP, this is the usual workflow:
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
The diff() method returns a DateInterval object containing parts such as:
yfor yearsmfor monthsdfor days
Mental Model
Think of date difference as a calendar-based journey, not simple arithmetic.
If you travel from one date to another, PHP does not just count raw days and guess the rest. Instead, it moves through the calendar in parts:
- First count full years
- Then count remaining full months
- Then count leftover days
So the gap is like saying:
- "I walked 2 full years"
- "Then 3 more full months"
- "Then 2 extra days"
That is why DateTime and diff() are useful: they understand the calendar rules for you.
Syntax and Examples
Basic syntax
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
echo $interval->y . ' years, ' . $interval->m . ' months, and ' . $interval->d . ' days';
Example output
2 years, 3 months, and 2 days
Full beginner-friendly example
<?php
$startDate = '2007-03-24';
$endDate = '2009-06-26';
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$interval = $start->diff();
->y . . ->m . . ->d . ;
Step by Step Execution
Consider this code:
<?php
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
echo $interval->format('%y years, %m months, and %d days');
Step 1: Create the start date
$start = new DateTime('2007-03-24');
PHP creates a DateTime object representing March 24, 2007.
Step 2: Create the end date
$end = new DateTime('2009-06-26');
PHP creates another DateTime object representing June 26, 2009.
Step 3: Calculate the difference
Real World Use Cases
Date difference calculations are common in real applications.
Common examples
- Age calculation: find a person's age from their birth date
- Subscriptions: show how long a user has been subscribed
- Projects: calculate duration between start and end dates
- Booking systems: measure time between reservation dates
- HR software: calculate employee service length
- Reporting tools: show how long ago an event happened
Example: age calculation
<?php
$birthDate = new DateTime('1995-08-10');
$today = new DateTime();
$age = $birthDate->diff($today);
echo 'Age: ' . $age->y . ' years';
Example: membership duration
<?php
$joined = new DateTime('2022-01-15');
$now = new DateTime();
$membership = ->();
->();
Real Codebase Usage
In real PHP projects, developers usually do more than just call diff(). They combine it with validation, formatting, and business rules.
Common patterns
Validation before calculating
<?php
$startDate = '2007-03-24';
$endDate = '2009-06-26';
$start = DateTime::createFromFormat('Y-m-d', $startDate);
$end = DateTime::createFromFormat('Y-m-d', $endDate);
if (!$start || !$end) {
die('Invalid date format.');
}
$interval = $start->diff($end);
This avoids calculating with invalid inputs.
Guard clauses
<?php
function getDateDifference(string $startDate, ):
{
= ::(, );
= ::(, );
(! || !) {
;
}
= ->();
->();
}
Common Mistakes
1. Treating date strings like normal strings
Broken code:
<?php
$start = '2007-03-24';
$end = '2009-06-26';
echo $end - $start;
Why it is wrong:
- These are strings, not date objects
- Subtracting them does not produce a meaningful calendar difference
Use this instead:
<?php
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
2. Assuming every month has the same number of days
Broken idea:
<?php
$totalDays = 824;
$months = $totalDays / 30;
Why it is wrong:
Comparisons
| Approach | Best for | Pros | Cons |
|---|---|---|---|
DateTime + diff() | Most date difference tasks | Accurate, built-in, calendar-aware | Slightly more code than simple subtraction |
| Unix timestamps | Total seconds or days | Good for exact time differences | Not ideal for years/months/days calendar output |
| Manual string parsing | Rarely recommended | Can help in learning formats | Easy to get wrong |
DateInterval parts vs total days
| Value | Meaning |
|---|---|
$interval->y |
Cheat Sheet
Quick syntax
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
Useful properties
$interval->y; // years
$interval->m; // months
$interval->d; // days
$interval->days; // total days
$interval->invert; // 1 if negative, 0 if positive
Quick formatting
echo $interval->format('%y years, %m months, %d days');
Parse known format safely
$start = DateTime::createFromFormat('Y-m-d', );
FAQ
How do I calculate the difference between two dates in PHP?
Use DateTime objects and the diff() method:
$start = new DateTime('2007-03-24');
$end = new DateTime('2009-06-26');
$interval = $start->diff($end);
How do I get years, months, and days separately in PHP?
Read them from the DateInterval object:
$interval->y;
$interval->m;
$interval->d;
What is the difference between $interval->d and $interval->days?
$interval->dis the remaining day part$interval->daysis the full total number of days between the dates
Can I calculate date differences using strtotime()?
Mini Project
Description
Build a small PHP utility that accepts two dates and prints a human-readable difference such as 2 years, 3 months, 2 days. This demonstrates how to parse date input, validate it, calculate a difference with DateTime::diff(), and format the result cleanly.
Goal
Create a reusable PHP function that returns the difference between two Y-m-d dates in a readable format.
Requirements
- Accept two date strings in
Y-m-dformat. - Validate both dates before calculating the difference.
- Return the result as years, months, and days.
- Handle reversed dates safely.
- Print an error message if either date is invalid.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.