How to get the Hours Difference (in HH:MM format) in PHP
It’s very simple to get the difference in hours using PHP. Here’s a quick function that takes two time strings and returns the difference:
function timeDiff($firstTime, $lastTime) {
$firstTime = strtotime($firstTime);
$lastTime = strtotime($lastTime);
$timeDiff = $lastTime - $firstTime;
return $timeDiff;
}
echo (timeDiff("10:00", "12:00") / 60) / 60;
This converts both times to Unix timestamps using strtotime(), subtracts them to get the difference in seconds, and then divides by 3600 (60×60) to get hours.
This works well for simple time comparisons within the same day. If you’re working with dates across midnight or need more precision, consider using PHP’s DateTime class instead:
$start = new DateTime("10:00");
$end = new DateTime("12:00");
$diff = $start->diff($end);
echo $diff->format('%H:%I');
The DateTime approach handles edge cases better and gives you a proper DateInterval object to work with.