I am trying to calculate the total hours worked per day per employee, having as data, entry time, lunch time, meal finish time and departure time. Leaving this data like this:
Check in: 08:00:00 AM
Lunch: 01:00:00 PM
End of lunch: 01:45:00 PM
Work output: 05:00:00 PM
To calculate the hours worked in the day, I want to obtain the difference between the start time and the lunch hour, then the difference between the lunch finish time, which is when he returns to work, and the end time of the day. day of work, I have done this 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 it is returning the differences incorrectly, for example from 08 am to 01 pm it returns 7. And it would have to return 5, because there are 5 hours of difference. I don't know why this is happening to me, I have searched and tried in other ways but without success. By the way, the database fields are of type time.
I pass the data 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 fetched from the database, and each field is of type time, and is stored in this format hh:ii:ss without further ado. At the time of bringing them through the query, I print them after going through the array that the query returns, the way I print them is like this:
<?php echo $key['login'] . ' AM'; ?>
And so on with the rest. And I have done echo of each field and it shows them like this:
Alejo, according to the data you give:
The worker has worked a total time of 8 hours and 15 minutes .
One way to do the calculations is by differences in seconds, taking a timestamp of the objects.
Take a look at this code... in the comments I show what I said above.
I have also relied on
DateTime::createFromFormat('H:i A', $h1)
to create the date objects as you have presented in the question. That can vary, depending on how the data is stored in the database.Result: