-3
Hello person I’m having a little trouble calculating valid dates
Calculating days
function CalculaDias($xDataInicial, $xDataFinal){
$time1 = dataToTimestamp($xDataInicial);
$time2 = dataToTimestamp($xDataFinal);
$tMaior = $time1>$time2 ? $time1 : $time2;
$tMenor = $time1<$time2 ? $time1 : $time2;
$diff = $tMaior-$tMenor;
$numDias = $diff/86400;
return $numDias;
}
Calculating useful days
function DiasUteis($yDataInicial,$yDataFinal){
$diaFDS = 0; //dias não úteis(Sábado=6 Domingo=0)
$calculoDias = CalculaDias($yDataInicial, $yDataFinal); //número de dias entre a data inicial e a final
$diasUteis = 0;
while($yDataInicial!=$yDataFinal){
$diaSemana = date("w", dataToTimestamp($yDataInicial));
if($diaSemana==0 || $diaSemana==6){
//se SABADO OU DOMINGO, SOMA 01
$diaFDS++;
}else{
//senão vemos se este dia é FERIADO
for($i=0; $i<=11; $i++){
if($yDataInicial==Feriados(date("Y"),$i)){
$diaFDS++;
}
}
}
$yDataInicial = Soma1dia($yDataInicial); //dia + 1
}
return $calculoDias - $diaFDS;
}
the problem is time to make the calculation of difference of days... I’m using this stretch to catch the first and last day of the month
//primeiro dia do mes
$date = new DateTime('now');
$date->modify('first day of this month');
$primeiro = $date->format('d/m/Y');
//ultimo dia do mes
$date = new DateTime('now');
$date->modify('last day of this month');
$ultimo= $date->format('d/m/Y');
then after taking the two values is returning and calling the function
$diasUteis = DiasUteis($DataInicial, $DataFinal);
$diasNormal = CalculaDias($DataInicial, $DataFinal);
What’s happening is, it returns like this
30 days between 01/12/2020 and 31/12/2020; 21 working days between 01/12/2020 and 31/12/2020;
then you mean he’s ignoring it one day... I already took a look at other posts but the same problem is happening, in this case is skipping a useful day, someone can help me ?
"30 days between 01/12/2020 and 31/12/2020" - It makes sense. If you are on day 1 and add up 30 days, the result is day 31. So the difference between days 1 and 31 is 30 days. Of course date arithmetic is confusing and often counter-intuitive, and each language/API usually does the calculations the way it thinks best. But anyway, this is the way PHP calculates, and if you want it to consider an extra day, you have to add 1 manually.
– hkotsubo