Calculate the difference in working hours between two dates

3

I need to calculate the difference in working hours between two dates

ex:

$dataIni = '201705151330';
$dataFim = '201705161230'; 

Until then I can solve it with the following code:

$dataIni = '201705151330';
$dataFim = '201705161230';  

$datatime1 = new DateTime($dataIni);
$datatime2 = new DateTime($dataFim);


$data1  = $datatime1->format('Y-m-d H:i:s');
$data2  = $datatime2->format('Y-m-d H:i:s');  

$data1 = strtotime($data1);
$data2 = strtotime($data2);

$nHoras   = ($data2 - $data1) / 3600;
$nMinutos = (($data2 - $data1) % 3600) / 60;
$total = sprintf('%02d:%02d', $nHoras , $nMinutos);

echo $total;

But I need to take into account the shift from 07:30 to 12:00 and from 13:30 until 17:48 , ie you need to discount lunch and unpaid hours. How can I solve this in PHP?

    
asked by anonymous 15.05.2017 / 21:59

1 answer

2

You can solve this problem by making use of the native classes that PHP offers to handle Date / Time .

According to the description of your problem a possible solution would be to calculate the number of minutes between two dates where you should only consider the period between the defined shifts:

<?php

$dataIni = '201705151330';
$dataFim = '201705161230';

$datatime1 = new DateTime($dataIni);
$datatime2 = new DateTime($dataFim);

$intervaloEmMinuto = new DateInterval('PT1M');
$periodo = new DatePeriod($datatime1, $intervaloEmMinuto, $datatime2);
$minutos = 0;
foreach ($periodo as $data) {
        /* @var $data \DateTime */
        $dataEmMinuto = clone $data;

        $inicioDoPrimeiroTurno = clone $dataEmMinuto->setTime(7, 30, 0);
        $fimDoPrimeiroTurno = clone $dataEmMinuto->setTime(12, 0, 0);
        $inicioDoSegundoTurno = clone $dataEmMinuto->setTime(13, 30, 0);
        $fimDoSegundoTurno = clone $dataEmMinuto->setTime(17, 48, 0);

        if (($inicioDoPrimeiroTurno < $data && $data < $fimDoPrimeiroTurno) || ($inicioDoSegundoTurno < $data && $data < $fimDoSegundoTurno)) {
                $minutos++;
        }
}

$intervalo = new DateInterval("PT{$minutos}M");
$data = new DateTime();
$dataAtual = clone $data;
$data->add($intervalo);
$horasUteisEntreDuasDatas = $dataAtual->diff($data);
echo 'Horas úteis entre duas datas: '. $horasUteisEntreDuasDatas->format('%d dias %H horas %i minutos');
    
25.05.2017 / 08:16