php – Calculate percentage of hours

Question:

How to calculate percentage between two times?

I tried like this and it didn't work:

$tempo_total= "00:10:00";
$tempo_realizado= "00:05:00";

$percent= round((strtotime($tempo_realizado)/strtotime($tempo_total))*100);

Does not work.

Answer:

In this case, I think you should convert the times to seconds and then do the calculation.

$tempo_total= "00:10:00";
$empo_realizado= "00:05:00";

$tt = time_to_sec($tempo_total);
$tr = time_to_sec($tempo_realizado);

$percent = round(($tr / $tt) * 100);

echo $percent;

function time_to_sec($time) {
    $hours = substr($time, 0, -6);
    $minutes = substr($time, -5, 2);
    $seconds = substr($time, -2);

    return $hours * 3600 + $minutes * 60 + $seconds;
}

From the tests I did here it worked, and in this case it returned 50, which from what I understand, would be 50% of the time performed.

Scroll to Top