date_diff()
in PHP
-
Purpose:
date_diff()
calculates the difference between twoDateTime
objects. -
Returns:
ADateInterval
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"; // Output: 26 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";
// Output: 3 years, 3 months, 26 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"); // Output: +26 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"); // Output: -4 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 (+/-) |
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.