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 DateTime('2024-03-15');
$interval = $start->diff($end);
echo "Days between dates: " . $interval->days;
Output:
Days between dates: 14
Example when dates are reversed
<?php
$date1 = new DateTime('2024-03-15');
$date2 = new DateTime('2024-03-01');
$interval = $date1->diff($date2);
echo $interval->days;
Output:
14
The days property is the absolute total number of days. If you also want to know whether the result is negative, check the invert property:
<?php
$date1 = new DateTime('2024-03-15');
$date2 = new DateTime('2024-03-01');
$interval = $date1->diff($date2);
echo $interval->days; // 14
echo "\n";
echo $interval->invert; // 1 means date1 is later than date2
Older timestamp-based approach
<?php
$date1 = strtotime('2024-01-01');
$date2 = strtotime('2024-01-10');
$days = ($date2 - $date1) / 86400;
echo $days;
This can work for simple cases, but DateTime is generally preferred for clarity and correctness.
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 | Code | What happens |
|---|---|---|
| 1 | $start = new DateTime('2024-05-01'); | Start date is created |
| 2 | $end = new DateTime('2024-05-06'); | End date is created |
| 3 | $interval = $start->diff($end); | PHP calculates the gap |
| 4 | echo $interval->days; | Prints 5 |
Important note
The difference is based on the actual dates, not on manually counting strings or splitting text. That is why this approach is more reliable.
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('2024-08-15');
$nights = $checkIn->diff($checkOut)->days;
echo "Total nights: " . $nights;
In both cases, PHP handles the calendar rules for you.
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): ?int
{
if (!$date1 || !$date2) {
return null;
}
$start = new DateTime($date1);
$end = new DateTime($date2);
return $start->diff($end)->days;
}
Keeping the sign when needed
Sometimes developers need to know whether a date is in the past or future.
<?php
function signedDaysBetween(string $date1, string $date2): int
{
$start = new DateTime($date1);
$end = new DateTime($date2);
$interval = $start->diff($end);
return $interval->invert ? -$interval->days : $interval->days;
}
Using normalized dates
In many apps, developers normalize to midnight or use date-only values to avoid unexpected time effects.
<?php
$start = new DateTime('2024-06-01 00:00:00');
$end = new DateTime('2024-06-10 00:00:00');
This is especially useful in billing, scheduling, and reporting code.
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($date2);
echo $interval->days;
This may print 0 because the total difference is only 2 hours, not a full day.
If you only care about dates, use date-only values or set both times to midnight.
3. Expecting days to be negative
<?php
$date1 = new DateTime('2024-03-10');
$date2 = new DateTime('2024-03-01');
$interval = $date1->diff($date2);
echo $interval->days;
$interval->days is usually the absolute number of days. To check direction, use:
<?php
echo $interval->invert;
4. Trusting invalid date strings
Broken example:
<?php
$date = new DateTime('tomoroww');
Always validate user input when dates come from forms or APIs.
5. Mixing time zones accidentally
If one date uses one time zone and another uses a different time zone, results may differ from what you expect.
<?php
$utc = new DateTime('2024-01-01', new DateTimeZone('UTC'));
$local = new DateTime('2024-01-02', new DateTimeZone('America/New_York'));
When accuracy matters, use the same time zone for both dates.
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()
| Feature | DateTime | strtotime() |
|---|---|---|
| Readability | High | Medium |
| Built-in interval details | Yes | No |
| Safer for date logic | Yes | Less so |
| Best for real projects | Yes | Sometimes for simple tasks |
Absolute days vs signed days
| Need | Best choice |
|---|---|
| Just the gap in days | $interval->days |
| Need to know past or future | $interval->invert + $interval->days |
| Need years/months/days parts | Full DateInterval object |
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;
Simple helper function
function daysBetween(string $a, string $b): int
{
return (new DateTime($a))->diff(new DateTime($b))->days;
}
Best practice
- Prefer
DateTimeover manual second math - Use the same time zone when comparing dates
- If you only care about dates, avoid including times
- Validate user input before calculation
Edge cases
- Same date returns
0 - Reversed dates still give positive
days - Time values can change the result
- Daylight saving transitions can affect timestamp math
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.
How do I get signed day difference in PHP?
Use both days and invert:
$signed = $interval->invert ? -$interval->days : $interval->days;
Does PHP handle leap years automatically?
Yes. DateTime and diff() handle normal calendar rules, including leap years.
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
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
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.