Get time difference only from hours and minutes



 Problem:

I have two times one is $InTime : 12:55:10 and the other is $OutTime : 12:56:10
So I think calculating the time difference should be:
$TotalTimeInOffice = $OutTime - $InTime
I want in hours so I think this should be the result 00:01, but I am getting wrong result. With this calculation I am get 0 in the result, but why?
Here are some examples from database:
InTime is: 12:55:10
OutTime is: 12:56:09
Result Is: 0
InTime is: 12:24:45
OutTime is: 00:00:00
Result Is: -12
InTime is: 10:05:48
OutTime is: 10:06:11
Result Is: 0
and the PHP Code would be.
$timestart = $time_sheets->in_time;
$timestop = $time_sheets->out_time;
$time_diff = $timestop - $timestart ;
    echo "InTime is: $timestart <br />";
    echo "OutTime is: $timestop <br />";
    print_r('Result Is: '.$time_diff."<br />");





Answer :

this code fails when midnight is involved e.g. 12:24:45 - 00:00:00 returns -12:24:45. You need tocorrect the times if they are located on either side of midnight:

function getDuration($timestart, $timestop) {
    $time1 = new DateTime("today " . $timestart);
    $time2 = new DateTime("today " . $timestop);
    if ($time2 < $time1) {
        $time2 = new DateTime("tomorrow " . $timestop);
    }
    $time_diff = $time1->diff($time2);
    echo " InTime is: $timestart\n";
    echo "OutTime is: $timestop\n";
    echo " Result is: " . $time_diff->format("%r%H:%I:%S") . "\n\n";
}
getDuration("12:55:10", "12:56:09");
getDuration("12:24:45", "00:00:00");
getDuration("10:05:48", "10:06:11");
getDuration("11:00:00", "01:00:00");
Output:
 InTime is: 12:55:10
OutTime is: 12:56:09
 Result is: 00:00:59

 InTime is: 12:24:45
OutTime is: 00:00:00
 Result is: 11:35:15

 InTime is: 10:05:48
OutTime is: 10:06:11
 Result is: 00:00:23

 InTime is: 11:00:00
OutTime is: 01:00:00
 Result is: 14:00:00