How to calculate the number of hours between 2 dates in PHP?

Spread the love

Sometimes, we want to calculate the number of hours between 2 dates in PHP.

In this article, we’ll look at how to calculate the number of hours between 2 dates in PHP.

How to calculate the number of hours between 2 dates in PHP?

To calculate the number of hours between 2 dates in PHP, we can use the date diff method.

For instance, we write

$date1 = new DateTime("2022-04-12T12:30:00");
$date2 = new DateTime("2022-04-14T11:30:00");

$diff = $date2->diff($date1);

echo $diff->format("%a Day and %h hours");

to call $date2->diff with $date1 to return the $diff` interval object.

Then we call $diff.format to return the interval value in days and hours.

Conclusion

To calculate the number of hours between 2 dates in PHP, we can use the date diff method.

Leave a Reply

Your email address will not be published.