计算给定时间戳集的持续时间

时间:2012-07-13 11:00:59

标签: time php

我有一组intime和outtime,我想计算intime和outtime之间的持续时间,并添加所有持续时间以获得总持续时间。
例如:

Array
    (
    [1] => Array
        (
            ['intime'] => 1342086993
            ['outime'] => 1342087585
        )

    [3] => Array
        (
            ['intime'] => 1342087669
            ['outtime] => 1342096165
        )

    [5] => Array
        (
            ['intime'] => 1342096339
            ['outime'] => 1342096345
        )
    )

$total_duration = 0;
foreach($logArray as $log)
{
  $duration = $log['outime'] - $log['intime'];
  $total_duration += $duration;
}

$duration_hrs = $total_duration/3600;
echo 'Time spend in hrs :'.$duration_hrs;

但这并没有给我适当的持续时间。有没有其他方法可以这样做。

4 个答案:

答案 0 :(得分:2)

使用array_map首先将每个元素映射到持续时间,然后array_sum将它们相加:

$durations = array_map(function ($e) {
  return $e['outtime'] - $e['intime'];
}, $logArray);
$total_duration = array_sum($durations);

答案 1 :(得分:0)

$total_duration = 0;
foreach($logArray as $log)
{
  $duraton = $log['outtime'] - $log['intime'];
  $total_duration += $duration;
}
$duration_hrs = $total_duration/3600;
echo 'Time spend in hrs :'.$duration_hrs;

答案 2 :(得分:0)

您的语法免费脚本,对我很有用:

<?php

    $logArray = Array (
        1 => Array (
            'intime' => 1342086993,
            'outime' => 1342087585
        ),
        3 => Array (
            'intime' => 1342087669,
            'outime' => 1342096165
        ),
        5 => Array (
            'intime' => 1342096339,
            'outime' => 1342096345
        )
    );

    $total_duration = 0;
    foreach( $logArray as $log ) {
      $duration = $log[ 'outime' ] - $log[ 'intime' ];
      $total_duration += $duration;
        echo $duration / 3600 . "<br />";
    }

    $duration_hrs = $total_duration / 3600;
    echo 'Time spend in hrs: ' . $duration_hrs;

?>

输出:

0.16444444444444
2.36
0.0016666666666667
Time spend in hrs: 2.5261111111111 

好像你的时间格式不对:13, July 2012 04:04:32 PM应为13. July 2012 04:04:32 PM

strtotime('13. July 2012 04:04:32 PM')

正常工作。它应该1342195472代替你1342168834。因此,请检查生成错误微时间的时间格式

答案 3 :(得分:0)

你的代码中有一个简单的拼写错误。检查一下:

duraton vs duration

改变并且没事。