I need to calculate the difference between two times in hours. For example, the difference between 08:00:00 and 09:30:00 would be 1.5 hours.
I'm using the code below:
$time1 = '08:00:00';
$time2 = '09:30:00';
$difference = $time2 - $time1;
echo $difference;
Instead of getting 1.5 back as I'd expect, I'm getting 1. I'm sure this is a time formatting issue that someone can easily advise me on. Hopefully... :]
asked Apr 16, 2015 at 3:33
You can try my code
answered Feb 13, 2018 at 13:48
swathi_sriswathi_sri
4074 silver badges8 bronze badges
4
You have to dates and you want to calculate hours between those two dates. In the following you’ll see two methods to finds out hour difference between two dates Using strtotime[] function to find out hours is two steps
process See the following example how it works- [wpdm_file id=119] Output: How it works:Problem:
Solution:
Method 1: Using strtotime[] function
Difference between two dates is 25 hour[s]
Line 3:
We convert the first date to its
timestamp.Line 4:
We convert the second date to its timestamp.Line 5:
As the difference between two dates might be negative, we use absolute function, abs[], to get the value only. Then, we divided it by 60*60 to get the hours.
Method 2: Using diff[] method of DateTIme class from SPL
Calculating hours between two dates is 3 steps process-
- Convert each date to the DateTime object
- Calculate the day interval between two dates as object using diff[] method.
- Convert the Day interval object to its equivalent number of hours using format[] method.
[wpdm_file id=120]
Output:
Difference between two dates is 25 hour[s]
How it works:
Line 5-6:
We convert two dates to their respective DateTime objects.Line 7:
The diff[] method subtracts $datetimeObj1 from $datetimeObj2 and returns as an object.Line 9-11:
Here, we check if the interval between two dates is more than 1 day. If so, we convert the day to hours by multiplying it by 24. Here, format[‘%a’] returns total number of days.
Line 12-14:
The hour difference might
be less than 1 day. In that case we directly convert the interval object to hours. Here, format[‘%a’] returns total number of hours.
Line 16:
As the time difference between two dates might be day difference and hour difference between those, so we added the both of those to get the real hour difference.