date_diff() in PHP
-
Purpose:
date_diff()calculates the difference between twoDateTimeobjects. -
Returns:
ADateIntervalobject 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
?>
->daysgives 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 (+/-) |
0
likes
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
