Calculate hours in PHP?

I am developing an electronic point in PHP and would like to know how to do the two-hour Caculo being one of them is negative, for example:

Hourly load Day 1: -05:00:00

Hourly load Day 2: 08:00:00

How would the two-hour bill get the balance of hours?

Author: Marconi, 2015-07-07

2 answers

I made a code adapted from this Answer :

$horas = array(
    '-05:00:00',
    '08:00:00'
);

$seconds = 0;

foreach ( $horas as $hora )
{
    list( $g, $i, $s ) = explode( ':', $hora );
    if ($g < 0) {
        $i *= -1;
        $s *= -1;
    }
    $seconds += $g * 3600;
    $seconds += $i * 60;
    $seconds += $s;
}

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

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

Output :

3:0:0

IdeOne Example

 1
Author: Maicon Carraro, 2020-06-11 14:45:34

I did not quite understand the use of negative hours, in my view it would be better to have the number of hours you had access and deduct from the daily, weekly or monthly hours.

it seems that is answer in SOen solves your problem

$start = DateTime::createFromFormat('H:i:s', '11:30:00');
$start->add(new DateInterval('PT8H30M'));
$end   = DateTime::createFromFormat('H:i:s', '19:30:00');
$diff = $start->diff($end);
echo $diff->format('%r%H:%I');

I have not tested, but it seems you add 8 and a half hours and deduce from the final result.

However if you want something simpler, you can use unix-time, something like (using the function of this answer as get the format in hours when this exceeds 24?):

//Transforma as horas em "inteiro"
function toUnixTime($total) {
    $negativo = false;
    if (strpos($total, '-') === 0) {
        $negativo = true;
        $total = str_replace('-', '', $total);
    }

    list($horas, $minutos, $segundos) = explode(':', $total);
    $ut = mktime($horas, $minutos, $segundos);
    if ($negativo) {
        return -$ut;
    }

    return $ut;
}

//Gera horarios acima de 24 horas (para calculo total)
function getFullHour($input) {
    $seconds = intval($input);
    $resp = NULL;//Em caso de receber um valor não suportado retorna nulo

    if (is_int($seconds)) {
        $hours = floor($seconds / 3600);
        $mins = floor(($seconds - ($hours * 3600)) / 60);
        $secs = floor($seconds % 60);

        $resp = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
    }

    return $resp;
}

$dia1 = toUnixTime('-05:00:00');
$dia2 = toUnixTime('08:00:00');

//Compara os dois horarios
$calculo = $dia1 + $dia2;

echo getFullHour($calculo);
 1
Author: Guilherme Nascimento, 2017-05-23 12:37:23