PHP - Sum of hours for point system

Asked

Viewed 49 times

-2

I’m having a problem with the time balance calculation of my point system. Basically, I need to know how many hours an employee has, comparing the time he worked in the month with the time he was expected to work during that period.

In my code I can calculate quietly, even if the balance is negative, but at some point it gets lost and I could not understand yet, could help me?

//Teste funcionando
//$horasTrabalhadas = '140:30:00';
//$horasPrevistas = '141:30:00';
//Saldo de horas: -01:00:00

//Teste com erro
$horasTrabalhadas = '141:50:00';
$horasPrevistas = '144:00:00';
// Resultado esperado: 02:10 // Resultado que está aparecendo: 03:50

echo "Saldo de horas: " . calculaTempo($horasPrevistas, $horasTrabalhadas);

function calculaTempo($hora_inicial, $hora_final) {
    $i = 1;
    $tempo_total='';

    $tempos = array($hora_final, $hora_inicial);

    foreach($tempos as $tempo) {
        $segundos = 0;

        list($h, $m, $s) = explode(':', $tempo);

        $segundos += $h * 3600;
        $segundos += $m * 60;
        $segundos += $s;

        $tempo_total[$i] = $segundos;

        $i++;
    }

    $segundos = $tempo_total[1] - $tempo_total[2];

    $horas = floor($segundos / 3600);
    $segundos -= $horas * 3600;
    $minutos = str_pad((floor($segundos / 60)), 2, '0', STR_PAD_LEFT);
    $segundos -= $minutos * 60;
    $segundos = str_pad($segundos, 2, '0', STR_PAD_LEFT);

    return "$horas:$minutos:$segundos";
}

From now on I thank you all. :)

  • See help: https://answall.com/a/388495/112052

  • Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To understand what kind of question serves the site and, consequently, avoid closures and negativities worth reading What is the Stack Overflow and the Stack Overflow Survival Guide (summarized) in Portuguese.

1 answer

-4


I assumed that you are only used this for study purposes so I will not put into debate that this is not the best way to store time to perform calculations with hours, days etc to avoid Pogs like this. Done that come on. I took the liberty of bringing in the negative or positive hours balance;

<?php

function calculaTempo($horasPrevistas, $horasTrabalhadas) {

    $horasPrevistas  = asSeconds($horasPrevistas);
    $horasTrabalhadas    = asSeconds($horasTrabalhadas);
    $segundos   = $horasPrevistas - $horasTrabalhadas;
    $deveHoras  = $horasPrevistas > $horasTrabalhadas;
    $segundos   = getFullHour($segundos);
    var_dump($segundos);
    if ($deveHoras) {
        $data = ['saldo_negativo' => $segundos];
        return $data;
    }

    $data = ['saldo_positivo' => $segundos];
    return $data;
 }


function getFullHour($seconds) {
    $seconds = intval($seconds); //Converte para inteiro

    $negativo = $seconds < 0; //Verifica se é um valor negativo

    if ($negativo) {
        $seconds = -$seconds; //Converte o negativo para positivo para poder fazer os calculos
    }

    $horas = floor($seconds / 3600);
    $min = floor(($seconds - ($horas * 3600)) / 60);
    $sec = floor($seconds % 60);

    $sign = $negativo ? '-' : ''; //Adiciona o sinal de negativo se necessário

    return sprintf('%02d:%02d:%02d', $horas, $min, $sec);
}

function asSeconds($totalTime)
{
    $segundos = 0;
    list($h, $m, $s) = explode(':', $totalTime);
    $segundos += $h * 3600;
    $segundos += $m * 60;
    $segundos += $s;
    return $segundos;
}



$trabalhadas = '144:50:00';
$previstas = '144:00:00';

$calculo = calculaTempo($previstas, $trabalhadas);

if (!empty($calculo['saldo_negativo'])) {
    echo "Saldo de horas negativo é : " . $calculo['saldo_negativo'] . PHP_EOL;
} else {
    echo "Saldo de horas positivo é : " . $calculo['saldo_positivo'] . PHP_EOL;
}

Part of that answer is in this post /a/290020/4800 Consider giving +1 if you find it useful :)

  • I thank Mark immensely, that’s right. A hug.

  • Honestly I think the OS should ask the "down voter" the reason and show the author of the post/ answer the reasons . Some codes are for the purpose of studying and learning the language and this example I did was thinking about it. Things like this only discourage the forum from growing, since we use some time to respond

  • truth man, I honestly didn’t understand this amount of down voter, who voted should at least justify.

Browser other questions tagged

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