문제

I need to add multiple time values as in Hours:mins, so I use

strtotime($value1) + strtotime($value2)

to add all of them, how do I put them back as hours:mins ?

cant use

date("h:i")

it only works if hours < 24.

I appreciate your help. Thanks

도움이 되었습니까?

해결책 3

The function strtotime() returns the time in seconds since January 1 1970 00:00:00 UTC. So adding the return value of this function might not do what you would expect.

Instead of using the date functions we can manipulate the string and perform some basic arithmetic operations:

<?php
$value1 = "12:44";
$value2 = "13:47";

$arr1 = explode(':', $value1);
$arr2 = explode(':', $value2);

$totalMinutes = (int)$arr1[0] * 60 + (int)$arr1[1] + (int)$arr2[0] * 60 + (int)$arr2[1];

$hours = (int) ($totalMinutes / 60);
$minutes = $totalMinutes % 60; // Modulus: remainder when dividing with 60

echo $hours . ':' . $minutes;
?>

다른 팁

Here is an function that will sum all your time values in format HH:MM:

function sum_time() {
    $i = 0;
    foreach (func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }
    if ($h = floor($i / 60)) {
        $i %= 60;
    }
    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06

demo

Try this :

function time_convert($s) { 
    $m = 0; $hr = 0; $td = "now";
    if ($s > 59) { 
        $m = (int)($s/60); 
        $s = $s-($m*60); // sec left over 
        $td = "$m min"; 
    } 
    if ($m > 59) { 
        $hr = (int)($m / 60); 
        $m = $m - ($hr*60); // min left over 
        $td = "$hr hr"; 
        if ($hr > 1) {
            $td .= "s";
        }
        if ($m > 0) {
            $td .= ", $m min";
        }
    } 

    return $td; 
} 

And use it:

$time = (int) strtotime($v1) + strtotime($v2);
echo time_convert($time);

May it helps

Another way with DateTime

$dt1 = new DateTime($value1);
$dt2 = new DateTime($value2);
$interval = $dt1->diff($dt2);
echo $interval->format('%a day(s) %h hour(s) %i minute(s)') . '<br />';
echo ($interval->format('%a') * 24 + $interval->format('%h')) . ' hour(s) ';
echo $interval->format('%i minute(s)');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top