Calculate hours in PHP?

2

I'm developing an electronic dot in PHP and would like to know how to do the two-hour Cachulo, one of which is negative, for example:

Day 1: -05: 00: 00

Hours day 2: 08:00:00

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

    
asked by anonymous 07.07.2015 / 23:32

2 answers

1

I made an adapted code for this answer : p>

$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

    
08.07.2015 / 00:00
1

I did not understand the use of negative hours, in my opinion 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 this answer is in the 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 did not test, but apparently you add 8 ½ hours and deduce the final result.

However if you want something simpler, you can use unix-time, something like (using the function of this response How get the format in hours when it 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);
    
08.07.2015 / 00:13