Skip to content
Advertisement

Difference between sum of hours and minutes using php

I want to calculate total number of hours and minutes difference with another total number of hours and minutes, For example:

$firsttotal = 181:33; ( 181 hours and 33 minutes)
$secondtotal = 315:00; (315 hours and 0 minutes)

so i want a way for calculating its difference like

$difference = 134:07 (134 hours and 7 minutes is the correct answer)

As php strtotime is not converting it and also php date function is not working on this.

Advertisement

Answer

The answer is (based on the two inputs) 133:27, not 134:07.

In PHP, you can do the following with minimal data checking.

// 181 hours and 33 minutes
$firsttotal = "181:33";
// 315 hours and 0 minutes
$secondtotal = "315:00";

// Convert to min.
// Assumes $str is a time in hhh:mm format only.
// For example, "181:33" is 181 hours and 33 min.
function toMin($str) {
    $tmp = explode(":",$str);
    return $tmp[1] + (60 * $tmp[0]);
}

// Return the difference in two min counts in HHH:MM format.
function diffToHHMM($min1,$min2) {
    $diff = $min2 - $min1;
    $h = floor($diff / 60);
    $m = ($diff % 60);
    return $h.":".$m;
}

$val1 = toMin($firsttotal); 
$val2 = toMin($secondtotal);

echo diffToHHMM($val1, $val2);
// Result: 133:27
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement