Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

If you’re working with database data a lot in your applications, especially for reporting scenarios, you will run into having to get differences between dates once or twice. PHP handles this function very well and in my opinion very easily.

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.

The post Get The Difference Between Two Date Times In PHP Using Diff() appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

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

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×