PHP Calculating time difference

Associate
Joined
26 Oct 2003
Posts
1,107
I'm trying to make a function in PHP that will accept a time in a 24 hour format (HH:MM) then calculate the difference from the current time. I've found lots of useful looking bits of code on the net, but I don't have a clue about PHP when it comes to comparing times.

The function will also need to work when the input time is after midnight and the current time is before (ie. now = 23:55 input = 00:10 will return 15)

Can anyone point me in the right direction?

Thanks for any help,
Alex
 
I've figured something out which seems to work :)

PHP:
<?php
function timeDiff($inputTime)
{

$hour = substr($inputTime, 0, 2);
$mins = substr($inputTime, 3, 4);

$difference = (mktime($hour,$mins) - mktime()) / 60;

return $difference;
}
?>
 
You can then recreate the $difference in the HH:MM format with the following:
Code:
$difference = date("H:i", (mktime($hour,$mins) - mktime()) / 60);

However, without knowing the date, you'll get inaccuracies with the 23:55 - 00:15 scenario. :)
 
Back
Top Bottom