Question
How can I find the number of days between two dates in PHP?
For example, I want to compare two dates and get the difference in days in a reliable way. What is the correct approach in PHP, and which built-in date tools should I use?
Short Answer
By the end of this page, you will understand how to calculate the number of days between two dates in PHP, especially using DateTime and diff(). You will also learn how the result works, how to handle date order, and what mistakes to avoid when working with dates.
Concept
In PHP, the safest and most readable way to find the number of days between two dates is to use the DateTime class together with the diff() method.
DateTime represents a date and time value, and diff() compares two DateTime objects and returns a DateInterval object. That interval contains useful information such as:
- years
- months
- days
- hours
- whether the result is negative
For day differences, the most useful property is often days, which gives the total number of days between the two dates.
This matters because dates are more complicated than simple numbers. Different months have different lengths, leap years exist, and time zones can affect results. PHP's built-in date classes handle these rules for you, which makes your code more accurate and easier to maintain.
A common beginner approach is to subtract Unix timestamps and divide by 86400, but that can become unreliable when time zones or daylight saving changes are involved. For most application code, DateTime is the better choice.
Mental Model
Think of two dates as two points on a calendar.
Using DateTime and diff() is like asking PHP to count the calendar distance between those two points for you.
Instead of manually counting days or doing math with seconds, you hand both dates to PHP and say:
- "Here is the start date"
- "Here is the end date"
- "Tell me the difference"
PHP then returns the gap in a structured way, much like a travel summary:
- 0 years
- 2 months
- 5 days
- total: 66 days
This is easier and safer than trying to do calendar math by hand.
Syntax and Examples
Basic syntax
$date1 = new DateTime('2024-01-01');
$date2 = new DateTime('2024-01-10');
$interval = $date1->diff($date2);
echo $interval->days;
This prints:
9
Why it works
new DateTime('2024-01-01')creates the first datenew DateTime('2024-01-10')creates the second date$date1->diff($date2)compares the two dates$interval->daysgives the total difference in days
Example with formatted output
<?php
$start = new DateTime('2024-03-01');
$end = new ();
= ->();
. ->days;
Step by Step Execution
Example
<?php
$start = new DateTime('2024-05-01');
$end = new DateTime('2024-05-06');
$interval = $start->diff($end);
echo $interval->days;
Step by step
- PHP creates a
DateTimeobject for2024-05-01. - PHP creates another
DateTimeobject for2024-05-06. $start->diff($end)compares the two dates.- PHP builds a
DateIntervalobject containing the difference. $interval->daysreads the total number of days in that difference.- The result
5is printed.
Trace
| Line |
|---|
Real World Use Cases
Calculating the number of days between dates is common in real applications.
Common examples
- Booking systems: number of nights between check-in and check-out dates
- Subscription apps: days left until renewal or expiration
- Task management tools: days remaining until a deadline
- Reporting dashboards: difference between start and end dates for a report range
- HR systems: leave duration between two dates
- Invoice systems: payment overdue by a certain number of days
Example: subscription expiration
<?php
$today = new DateTime('today');
$expiresAt = new DateTime('2024-12-31');
$interval = $today->diff($expiresAt);
echo "Days remaining: " . $interval->days;
Example: hotel booking
<?php
$checkIn = new DateTime('2024-08-10');
$checkOut = new DateTime();
= ->()->days;
. ;
Real Codebase Usage
In real PHP projects, developers usually wrap date calculations in small helper functions or service classes so the logic stays consistent across the codebase.
Common patterns
Validation before calculation
Developers often validate input before creating DateTime objects.
<?php
function daysBetween(string $date1, string $date2): int
{
$start = new DateTime($date1);
$end = new DateTime($date2);
return $start->diff($end)->days;
}
Guard clauses
If input may be missing, guard clauses keep the function safe.
<?php
function daysBetweenOrNull(?string $date1, ?string $date2): ?
{
(! || !) {
;
}
= ();
= ();
->()->days;
}
Common Mistakes
1. Using raw second math for all cases
Broken example:
<?php
$days = (strtotime($date2) - strtotime($date1)) / 86400;
Why this can be a problem:
- daylight saving changes can affect the exact number of seconds in a day
- times may not both be midnight
- the result may be fractional
Better approach:
<?php
$days = (new DateTime($date1))->diff(new DateTime($date2))->days;
2. Forgetting that time affects the result
<?php
$date1 = new DateTime('2024-01-01 23:00:00');
$date2 = new DateTime('2024-01-02 01:00:00');
$interval = $date1->diff();
->days;
Comparisons
Comparing common approaches
| Approach | Example | Good for | Limitations |
|---|---|---|---|
DateTime + diff() | $a->diff($b)->days | Most PHP applications | Requires understanding DateTime objects |
strtotime() subtraction | ($b - $a) / 86400 | Very simple quick scripts | Can be less reliable with times and DST |
| Manual string parsing | Splitting YYYY-MM-DD yourself | Learning only | Error-prone and not recommended |
DateTime vs strtotime()
Cheat Sheet
Quick reference
Create dates
$date1 = new DateTime('2024-01-01');
$date2 = new DateTime('2024-01-10');
Get difference
$interval = $date1->diff($date2);
Total days
echo $interval->days;
Check direction
echo $interval->invert;
0= first date is earlier or same1= first date is later
Signed result
$signedDays = $interval->invert ? -$interval->days : $interval->days;
FAQ
How do I calculate days between two dates in PHP?
Use DateTime and diff():
$days = (new DateTime('2024-01-01'))->diff(new DateTime('2024-01-10'))->days;
What does $interval->days mean in PHP?
It is the total number of days between two dates in the DateInterval result.
Can diff() return a negative number of days?
The days property is usually absolute. To detect direction, check $interval->invert.
Is strtotime() good for finding date differences?
It can work for simple cases, but DateTime is usually a better and safer choice.
Why do I get 0 days when the dates are on different calendar dates?
Because the time difference may be less than 24 hours. If you only care about dates, compare date-only values or set both times to midnight.
Mini Project
Description
Build a small PHP utility that calculates the number of days between two user-provided dates. This demonstrates how to create DateTime objects, compare them with diff(), and display both the absolute and signed day difference.
Goal
Create a reusable PHP script that accepts two dates and prints the total number of days between them, including whether the second date is before or after the first.
Requirements
- Accept two date strings in
YYYY-MM-DDformat. - Convert both strings into
DateTimeobjects. - Calculate the difference using
diff(). - Print the absolute number of days.
- Also print a signed result that shows whether the second date is earlier or later.
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.