How to Get Time Difference in Hours and Minutes in PHP?

By Hardik Savani January 15, 2024 Category : PHP

Hey Dev,

Now, let's see post of php get time difference in hours and minutes. In this article, we will implement a php datetime difference in hours. step by step explain how to calculate hours difference between two dates in php. you can understand a concept of get hours difference between two dates php.

To get the time difference in hours and minutes using PHP, you can use the DateTime class. Here's an example:




/* Create two DateTime objects */

$startTime = new DateTime('2023-01-15 10:00:00');

$endTime = new DateTime('2023-01-15 14:30:00');

/* Calculate the difference */

$timeDifference = $startTime->diff($endTime);

/* Access the hours and minutes properties */

$hours = $timeDifference->h;

$minutes = $timeDifference->i;

/* Output the result */

echo "Time difference: $hours hours and $minutes minutes";



Time difference: 4 hours and 30 minutes

Replace the date and time in the DateTime constructor with your specific start and end times. The diff method calculates the difference between the two DateTime objects, and then you can access the h and i properties to get the hours and minutes, respectively.

Remember to customize the date and time formats according to your needs.

I hope it can help you...

Tags :