Calculate hours in PHP?

Asked

Viewed 1,234 times

2

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

Workload day 1: -05:00:00

Workload day 2: 08:00:00

How would the two hour bill get the hours balance?

  • 1

    Negative hours? How does this work, would it be hours that the user should, like he didn’t go to work? Wouldn’t it be better to just calculate the hours accessed and deduct from the weekly hours for example?

  • Good afternoon, the answer solved your problem?

2 answers

1

I made a code adapted from that reply:

$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}"; 

Exit:

3:0:0

Ideone Exemplo

1

I did not understand well the use of the 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.

Seems like that is answer 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 didn’t test it, but apparently 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 How to 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);

Browser other questions tagged

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