How to add php hours

Asked

Viewed 2,782 times

1

I am making a bank system of hours, where I have a case where an employee enters at 22:00 of one day and leaves at 07:00 of the other and would like to calculate the difference between these times, climbing the break time! The result should be 8:00 am, but it’s coming out at 9:00 pm

My code is like this :

$data1 = '21-03-2019';
$data2 = '22-03-2019';
$hora1 = '22:00';
$hora2 = '03:00';
$hora3 = '04:00';
$hora4 = '07:00';

$dateStart = new DateTime(''.$data1.''.$hora1.'');
$dateSai = new DateTime(''.$data2.''.$hora4.'');
$dateInter = new DateTime(''.$data2.''.$hora2.'');
$dateRet = new DateTime(''.$data2.''.$hora3.'');

$dateDiff = $dateStart->diff($dateSai);
$dateIntervalo = $dateInter->diff($dateRet);

if(strlen($dateDiff->h)<2)
{
    $horatrab1 = '0'.$dateDiff->h;
}
else
{
    $horatrab1 = $dateDiff->h;
}
if(strlen($dateDiff->i)<2)
{
    $mintrab1 = '0'.$dateDiff->i;
}
else
{
    $mintrab1 = $dateDiff->i;
}
echo $horastrabalhadas1 = $horatrab1 .":". $mintrab1. '<br />';

//intervalo
if(strlen($dateIntervalo->h)<2)
{
    $interhora = '0'.$dateIntervalo->h;
}
else
{
    $interhora = $dateIntervalo->h;
}
if(strlen($dateIntervalo->i)<2)
{
    $intermin = '0'.$dateIntervalo->i;
}
else
{
    $intermin = $dateIntervalo->i;
}
echo $intervalo = $interhora .":". $intermin. '<br />';


echo $horastrabalhadas = date('H:i', strtotime($horastrabalhadas1) - strtotime($intervalo));
  • Hi, check this out: https://www.oyagum.com/articulos/sumar-restar-horas-minutos-segundos-php/, this might be helpful.

1 answer

0


Well, I found it simpler to calculate the total hours separately from the interval and then perform a simple subtraction of the two, follows example:

$entrada = new DateTime('2019/03/22 22:30:00');
$saida = new DateTime('2019/03/23 07:07:00');

$diff_trabalhada = $entrada->diff($saida);
$horas_totais = ($diff_trabalhada->h * 60) + $diff_trabalhada->i; //quantidade de minutos entre a entrada e saída do funcionário na empresa

$saida_intervalo = new DateTime('2019/03/23 03:59:00');
$volta_intervalo = new DateTime('2019/03/23 04:05:00');

$diff_intervalo = $saida_intervalo->diff($volta_intervalo);
$horas_intervalo = ($diff_intervalo->h * 60) + $diff_intervalo->i; //quantidade de minutos do intervalo do funcionário

//subtraindo essas horas totais do intervalo temos a quantidade de horas trabalhadas
$horas_trabalhadas = $horas_totais - $horas_intervalo;
$horas = (int)($horas_trabalhadas/60); //horas inteiras trabalhadas
$minutos = $horas_trabalhadas % 60; //minutos trabalhados
echo "{$horas}:{$minutos}"; //concatenação entre os dois
  • Yes, but in case I would need the minutes and calculate the extra balance if the employee passes the 8 hours worked

  • @Edu I made the changes by adding the minutes

  • Thanks a friend, you helped a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.