date_diff()
in PHP
-
Purpose:
date_diff()
calculates the difference between two DateTime
objects.
-
Returns:
A DateInterval
object that contains years, months, days, hours, minutes, seconds, etc., showing the difference.
Basic Syntax:
date_diff(DateTime $datetime1, DateTime $datetime2, bool $absolute = false): DateInterval
$datetime1
, $datetime2
→ Two dates you want to compare.
$absolute
→ (optional) If true, always returns positive difference.
Simple Example 1: Difference in Days
<?php
$date1 = new DateTime("2025-04-01");
$date2 = new DateTime("2025-04-27");
$diff = date_diff($date1, $date2);
echo $diff->days . " days";
?>
->days
gives total number of days difference (absolute, without sign).
Example 2: Showing Years, Months, and Days
<?php
$date1 = new DateTime("2022-01-01");
$date2 = new DateTime("2025-04-27");
$diff = date_diff($date1, $date2);
echo $diff->y . " years, ";
echo $diff->m . " months, ";
echo $diff->d . " days";
?>
->y
→ years, ->m
→ months, ->d
→ days
Example 3: Formatting the Difference
You can use format()
to customize how you show the difference.
<?php
$date1 = new DateTime("2025-04-01");
$date2 = new DateTime("2025-04-27");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days");
?>
%R
→ shows the sign (+ or -)
%a
→ total days between dates
Example 4: Negative Difference
<?php
$date1 = new DateTime("2025-05-01");
$date2 = new DateTime("2025-04-27");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days");
?>
If the second date is earlier, you’ll get a negative difference.
Quick List of format()
options:
Symbol |
Meaning |
%Y |
Years |
%m |
Months (0-11) |
%d |
Days (0-30) |
%H |
Hours (0-23) |
%i |
Minutes (0-59) |
%s |
Seconds (0-59) |
%a |
Total days difference |
%R |
Sign (+/-) |