Sum hours of an array

Asked

Viewed 1,209 times

0

I need to total the column hora_agente of the kind time. And I need the return value to be in hours. May be greater than 24 hours.

In the example I did, it’s returning 5:55, and it should return 53:55. I believe that when it’s 24 hours, it resumes counting.

If someone knows how to do it directly in SQL, better yet, the database is informix.

inserir a descrição da imagem aqui

            $total_horas = 0;

            foreach ($dados_tempos as $t) {          

                $horariof = trim($t['HORA_AGENTE']);

                $partesf = explode(':', $horariof);
                $segundosf = $partesf[0] * 3600 + $partesf[1] * 60;

                $total_horas += $segundosf;
            }        

            $horas_geral = gmdate("h:i:s", $total_horas);

            echo $horas_geral;

            //resultado = 05:55:00
            //resultado esperado = 53:55

3 answers

1

Example - ideone

$times = array('24:10','8:25','6:45','7:05','7:00','0:30');

$seconds = 0;

foreach ( $times as $time )
{
list( $g, $i ) = explode( ':', $time );
$seconds += $g * 3600;
$seconds += $i * 60;
}

$hours = floor( $seconds / 3600 );
$seconds -= $hours * 3600;
$minutes = floor( $seconds / 60 );

echo "{$hours}:{$minutes}";

list - is a native element of the PHP language and allows you to perform value assignments of an array for a set of variables in a simplified way.

0

You can create a function to do this treatment, and just call it at the end of your loop.

function convertTime( $total_hours ) 
{
    $hours   = floor( $total_hours / 3600 );
    $minutes = floor( ( $total_hours - ( $hours * 3600 ) ) / 60 );
    $seconds = floor( $total_hours % 60 );

    return $hours . ":" . $minutes . ":" . $seconds;
}

Example of use:

echo convertTime( 194100 ); // 53:55:00

0

Your problem lies precisely in the function gmdate, as it will format a date from a timestamp (Unix Epoch). As in the example below:

gmdate("d/m/Y h:i:s", '1000000'); // 12/01/1970 01:46:40

You could add/divide/multiply the time you’ve already calculated to get to the final time. However, I don’t really like this annoyance, as it leaves aside what PHP has internally already implemented.

In this case, PHP has a specific class to work with time/date intervals, which is the class Dateinterval. However, it is not so trivial to work it for your specific case, because natively you cannot add one Dateinterval to another.

Another detail is the format that Dateinterval needs to be created, which is different from the traditional date format (let’s say so).

On the other hand, you can use the Datetime class together, which helps us to create a Dateinterval without changing the format from the database.

//é necessária uma data base (00:00:00) - $baseDate
//e uma data para adicionar/somar os tempos vindos do SGBD - $date
$baseDate = clone $date = \DateTime::createFromFormat('H:i:s' , '00:00:00');

//dados vindo do banco de dados
$array = [
    '04:30',
    '05:30',
    '04:23',
    '02:35',
    '01:50',
    '03:25',
    '03:40',
    '02:30'
];    

//percorre cada valor do array
foreach($array as $time)
{
    //cria-se o date time com o tempo informado
    $dateTime = \DateTime::createFromFormat('H:i' , $time);

    //realiza o diff com a $baseDate para criar o DateInterval
    $diff = $baseDate->diff($dateTime);

    //adiciona o diff ao DateTime que somará o tempo
    $date->add($diff);
}

//realiza o último diff entre o DateTime de soma e a base date
$interval = $baseDate->diff($date);

//DateInterval mantêm em dias (%a) tudo que for acima de 24 horas.
$hours = $interval->format('%H') + ($interval->format('%a') * 24);

//exibe o tempo
echo $hours.$interval->format(':%I'); // Saída: 28:23

The code was a little extended by the explanation, however, ends up using objects that can be reused for display and other calculations when necessary.

Browser other questions tagged

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