The diff Method of the DateTime Class
The diff
method of the DateTime
class takes another DateTime
object as a parameter and returns a DateInterval
object containing the difference between the dates. The difference can be obtained in various units (days, months, years, etc.).
Syntax
$interval = $datetime1->diff($datetime2);
Example
Let's calculate the difference between two dates:
<?php
$date1 = new DateTime('2023-01-01');
$date2 = new DateTime('2023-02-15');
$interval = $date1->diff($date2);
echo $interval->format('%R%a days');
?>
Code execution result:
'+45 days'
Example
Get the difference in months and days:
<?php
$date1 = new DateTime('2023-03-10');
$date2 = new DateTime('2023-05-25');
$interval = $date1->diff($date2);
echo $interval->format('%m months %d days');
?>
Code execution result:
'2 months 15 days'
Example
Date comparison including time:
<?php
$date1 = new DateTime('2023-01-01 10:00:00');
$date2 = new DateTime('2023-01-01 14:30:00');
$interval = $date1->diff($date2);
echo $interval->format('%h hours %i minutes');
?>
Code execution result:
'4 hours 30 minutes'
See Also
-
the
date
function,
which formats date and time -
the
strtotime
function,
which converts a string to a timestamp -
the
DateInterval
class,
which represents a date interval