Get The Difference Between Two Date Times In PHP Using Diff()

There are more than a handful of ways to get the difference between two date times using PHP. The native functions that PHP comes fresh out of the box with a function named diff() which is part of the DateTime class. The function even allows you to extract the difference in dates in the format of year, month, etc.

Utilizing the DateTime diff() function

Probably the most fluent and understandable method is to use the diff() function which is part of the DateTime object. This exposes the DateTime-Interval object. Although, having said all this, you do have to add a bit of math when it comes to comparing dates over more than a 24 hour period.

Initializing

$dtNow = new DateTime('2020-04-01 06:00:00');
$dtToCompare = new DateTime('2018-04-01 00:00:00');

$diff = $dtNow->diff($dtToCompare);

Now we have access to the diff() functions and can quickly access its values like below –

Get Diff in Years
echo $diff->y; // 2
Get Diff In Months
echo 12 * $diff->y + $diff->m; // 24
Get Diff In Days
echo $diff->days; // 731
Get Diff In Hours
echo $diff->h + ($diff->days * 24); // 17550
Get Diff In Minutes
echo (($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i); // 1053000
Get Diff In Seconds
echo ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i)*60 + $diff->s; // 63136800

 

Summary

As you can see, DateTime Diff is pretty simple to use and generally will please most use-cases. Although, having said this, the diff functionality is by no means the only way to calculate the difference between two dates in PHP.

There are some great community functions on the date_diff() documentation page which certainly worth a glance over.

Posted in PHP

Leave a Reply

Your email address will not be published.