I am trying to calculate the total hours worked of the day per employee, taking as data, time of entry, meal time, meal time and departure time. Keeping this data like this:
Entry: 08:00:00 AM
Food: 01:00:00 PM
End of meal: 01:45:00 PM
Work output: 05:00:00 PM
To calculate the hours worked in the day, I want to get the difference between the time of entry and the meal time, then the difference between the meal time when it goes back to work and the time of the end of the day of work, this I have done it in the following way:
function HorasTrabajadas($h1,$h2,$h3,$h4){
$horalogin = new DateTime($h1);
$horalunchstart = new DateTime($h2);
$horalunchend = new DateTime($h3);
$horalogout = new DateTime($h4);
$diferencia1 = $horalogin->diff($horalunchstart);
$diferencia2 = $horalunchend->diff($horalogout);
$hora1 = $diferencia1->format('%H');
$hora2 = $diferencia2->format('%H');
$horas = $hora1+$hora2;
return $horas . ' hours';
}
The problem is that he is giving me back the wrong differences, for example from 8 a.m. to 1 p.m. he returns me 7. And I would have to return 5, because they are 5 hours apart. I do not know why this is happening to me, I have searched and tried in other ways but without getting results. By the way, the fields of the bd are of type time.
The data was passed to the function in this way
if ($key['login'] != '00:00:00' and $key['lunch_start'] != '00:00:00' and $key['lunch_end'] != '00:00:00' and $key['logout']!='00:00:00') {
$horas = HorasTrabajadas($key['login'],$key['lunch_start'],$key['lunch_end'],$key['logout']);
$form = true;
} else {
$horas = 'The day is not complete';
$form = false;
}
Each data is brought from the database, and each field is of type time, and it is stored in this format hh: ii: ss without more. When I bring them through the query I print them after going through the array that returns the query, the way I print them is like this:
<?php echo $key['login'] . ' AM'; ?>
And so on with the rest. And I've done echo of each field and shows them like this: