【问题标题】:Calculate time difference and sum the results in PHP在 PHP 中计算时间差并对结果求和
【发布时间】:2014-08-15 05:05:07
【问题描述】:

我有一个包含时间数据的数组,像这样:

$time = [
    "10:05:32",
    "11:03:43",
    "13:43:16",
    "10:17:21"
];

现在我要计算$time[x] - 10:00:00,并将所有结果相加:00:05:32 + 01:03:43 + 03:43:16 + 00:17:21 (=5:09:52)

我在php.net上看过一些参考资料,但都是关于日期的,没有简单的时间计算的解决方案吗?

【问题讨论】:

  • 这不是一个真正的问题:date 存储日期和时间,因此将所有给定时间设置为 2000 年 1 月 1 日或其他时间......

标签: php arrays datetime


【解决方案1】:

我要做的是首先将它们转换为时间戳,然后映射差异然后总结它们。像这样:

$diff = '10:00:00';
$time = ["10:05:32", "11:03:43", "13:43:16", "10:17:21"];
$time = array_map(function($t) use ($diff){
    return strtotime($t) - strtotime($diff);
}, $time);

$time = gmdate('H:i:s', array_sum($time));
echo $time; // 05:09:52

【讨论】:

    【解决方案2】:

    试试下面的工作代码

    $time = array("10:05:32", "11:03:43", "13:43:16", "10:17:21");
    $seconds=0;
    foreach ($time as $value){
        list($h,$m,$s)=split(":",$value);       
        $seconds=$seconds+($s+($h*3600)+($m*60))-36000;
    }
    $output = gmdate("H:i:s", $seconds);
    echo $output;
    

    //输出是05:09:52

    【讨论】:

      【解决方案3】:
       function dateDifference($startDate, $endDate) 
              { 
                  $startDate = strtotime($startDate); 
                  $endDate = strtotime($endDate); 
                  if ($startDate === false || $startDate < 0 || $endDate === false || $endDate < 0 || $startDate > $endDate) 
                      return false; 
      
                  $years = date('Y', $endDate) - date('Y', $startDate); 
      
                  $endMonth = date('m', $endDate); 
                  $startMonth = date('m', $startDate); 
      
                  // Calculate months 
                  $months = $endMonth - $startMonth; 
                  if ($months <= 0)  { 
                      $months += 12; 
                      $years--; 
                  } 
                  if ($years < 0) 
                      return false; 
      
                  // Calculate the days 
                              $offsets = array(); 
                              if ($years > 0) 
                                  $offsets[] = $years . (($years == 1) ? ' year' : ' years'); 
                              if ($months > 0) 
                                  $offsets[] = $months . (($months == 1) ? ' month' : ' months'); 
                              $offsets = count($offsets) > 0 ? '+' . implode(' ', $offsets) : 'now'; 
      
                              $days = $endDate - strtotime($offsets, $startDate); 
                              $days = date('z', $days);    
      
                  return array($years, $months, $days); 
              } 
      

      这接受任何formats listed on this page,包括小时分秒,这就是您似乎拥有的...希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-13
        相关资源
        最近更新 更多