Sizzling Code
Sizzling Code

Reputation: 6090

Get time difference only from hours and minutes

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 />");

Upvotes: 0

Views: 77

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272406

Your code fails when midnight is involved e.g. 12:24:45 - 00:00:00 returns -12:24:45. You need to correct 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

Upvotes: 1

Sizzling Code
Sizzling Code

Reputation: 6090

// Change It
$time1 = new DateTime($timestart);
$time2 = new DateTime($timestop);
// $time_diff = $timestop - $timestart ;
$time_diff = $time1->diff($time2);
echo "InTime is: $timestart <br />";
echo "OutTime is: $timestop <br />";
print_r('Result Is: ' . $time_diff->format('%H:%I:%s') . "<br />");
// End of Change

Problem Solved with DateTime function, but if there is any other good/better way then please post that answer too..

Upvotes: 0

geekido
geekido

Reputation: 171

I guess you should convert it to time() using strtotime(); then use $timeOutTime - $timeInTime;

   $timestart = $time_sheets->in_time;
    $timestop = $time_sheets->out_time;
    $timestart = strtotime($timestart);
    $timestop = strtotime($timestop);
    $time_diff = $timestop - $timestart ;
    echo data("h:i:s",$time_diff);

this should work.

Upvotes: 0

Related Questions