0

Hi I have a two variable in 24 hour time format and want to compute the number of hours worked. But I get negative and wrong value

I'm using PHP and here's my code

$endtime = date( 'g:i A', strtotime( $itInfo['endTime'] ) );
$startTime = date( 'g:i A', strtotime( $itInfo['startTime'] ) );
$timeDiff = (strtotime($endtime) - strtotime($startTime))/60/60;
$total      = strtotime($endtime) - strtotime($startTime);
$hours      = floor($total / 60 / 60);
$minutes    = round(($total - ($hours * 60 * 60)) / 60);

echo "FROM ".$itInfo['startTime']." TO ".$itInfo['endTime']." (".$hours.'.'.$minutes."hours)";`

Here's the output FROM 22:00 TO 03:00 (-19.0hours) which is wrong the output should be 5 Hours.

potashin
  • 44,205
  • 11
  • 83
  • 107

2 Answers2

0

Try this:

$timeDiff = strtotime($itInfo['endTime']) - strtotime($itInfo['startTime']);

echo substr('00'.($timeDiff / 3600 % 24),-2)
    .':'. substr('00'.($timeDiff / 60 % 60),-2)
    .':'. substr('00'.($timeDiff % 60),-2);
Ole Sauffaus
  • 534
  • 3
  • 13
0

As others have stated, best to work with timestamps. But with your current code, you should be able to add this right before the echo:

if ($itInfo['startTime'] > $itInfo['endTime']) {
    $hours = 24 - $hours;
}

This would be: 24 - 19 = 5.

Also, be sure to take add abs() in your $total variable as well:

$total = abs(strtotime($endtime) - strtotime($startTime));

camelCase
  • 5,460
  • 3
  • 34
  • 37