Reputation: 1382
I have a calendar in which the user can save events. Each event has a $start_time
and an $end_time
. The times are saved in HH:mm:ss
format. Is there a function which calculates the differnce between the two times but takes into account only the hours, not minutes and seconds? For instance if $start_time = 09.00.00
and $end_time = 12.00.00
then difference(start_time, end_time)
should be 3
.
Upvotes: 0
Views: 76
Reputation: 17598
The DateTime
class has a method to compare dates -
$start = new DateTime('04:13:41'); // accepts the same formats as strtotime
$end = new DateTime('08:31:13');
$diff = $start->diff($end); // pass 'true' as the second param for absolute
echo $diff->h; // 'h' contains the difference in hours
Upvotes: 1
Reputation: 9125
You can calculate the difference by parsing the string into a numeric format with the strtotime()
function, then calculate the time delta and parse it back to a string representation with date()
, like so:
$delta = strtotime($end_time) - strtotime($start_time);
$timediff = date('H', $delta);
Or you can strip out the seconds and minutes before the substraction like so:
$end_time_hrs = date('H', strtotime($end_time));
$start_time_hrs = date('H', strtotime($start_time));
And then the difference:
$delta = strtotime($end_time_hrs) - strtotime($start_time_hrs);
$timediff = date('H', $delta);
Upvotes: 0