Question:
I need to calculate the difference in working hours between two dates
ex:
$dataIni = '201705151330';
$dataFim = '201705161230';
So far 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 must take into account that the shift is from 7:30 am to 12:00 pm and from 1:30 pm to 5:48 pm , that is, it is necessary to discount lunchtime and hours not worked. How can I solve this in PHP?
Answer:
You can solve this problem by making use of the native classes that PHP offers to manipulate 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');