Get amount of hours between 2 hours
If you would like to get the amount of hours between 10:00 and 12:00 then use this!
I needed this for a timesheet calculator where users entered start and end times. The function converts both time strings to Unix timestamps using strtotime, subtracts them, and returns the difference in seconds. The division by 3600 (60*60) at the end converts seconds to hours.
Note that this only works for times within the same day. If you need to handle overnight spans (e.g., 23:00 to 02:00), you’ll need to add date handling with DateTime objects instead. For PHP 5.3+, the DateTime::diff() method is a cleaner alternative that handles edge cases better.
function timeDiff($firstTime,$lastTime) {
$firstTime=strtotime($firstTime);
$lastTime=strtotime($lastTime);
$timeDiff=$lastTime-$firstTime;
return $timeDiff;
}
echo (timeDiff("10:00","12:00")/60)/60;