【问题标题】:php calculate total hours and minutes and secondsphp计算总小时和分钟和秒
【发布时间】:2019-01-16 06:24:44
【问题描述】:

我估计总共有几个小时,其中包括几个小时 - 几分钟 - 几秒钟。 像这样: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;
            }
        }

【问题讨论】:

    标签: php time


    【解决方案1】:

    除以 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>';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 1970-01-01
      相关资源
      最近更新 更多