首页 > 解决方案 > php计算总小时和分钟和秒

问题描述

我估计总共有几个小时,其中包括几个小时 - 几分钟 - 几秒钟。像这样:170: 156: 230 表示 170 小时 156 分 230 秒。现在我怎么能把这个值变成这样的东西:172:59:59。总秒数不应超过 59 秒。如果更多,溢出量将增加到一分钟。我会对分钟的总和做同样的事情:也就是说,分钟的总和永远不会超过 59,如果是,溢出的量将被添加到总小时数中。我已经这样做了(当然,这并不完美)

$raw_times = ['h'=>102, 'm'=>353, 's'=>345];

foreach (array_reverse($raw_times) as $type => $value) {
     switch ($type) {
         case 's':
             if (60 < $value) {
                 while ((60 < $value) && (0 <= $value)) {
                     $sec_overlap += 60;
                     $value -= 60;
                 }

                $raw_times['s'] = $value;
                $raw_times['m'] += $sec_overlap;
                return $raw_times;
            }
                break;
                case 'm':
                    // some thing like above...
                    break;
            }
        }

标签: phptime

解决方案


简单计算除以 60。

function convert($param) {
    $hms = array_map('intval', explode(':', $param));
    $hms[1] += floor($hms[2] / 60);
    $hms[2] %= 60;

    $hms[0] += floor($hms[1] / 60);
    $hms[1] %= 60;

    return implode(': ', $hms);
}

echo convert('170: 156: 230 ');

如果将参数用作数组:

function convert($hms) {
    $hms['m'] += floor($hms['s'] / 60);
    $hms['s'] %= 60;

    $hms['h'] += floor($hms['m'] / 60);
    $hms['m'] %= 60;

    return $hms;
}

print '<pre>';
print_r(convert(['h'=>102, 'm'=>353, 's'=>345]));
print '</pre>';

推荐阅读