在 Laravel 中求和时间的最佳方法?

Best way to sum time in Laravel?

我有一个名为 transactions 的 table,其中有两个与我的问题相关的字段,_start_timestamp_ 和 _end_timestamp_。我需要对 _end_timestamp_ 不为空的所有事务之间传递的时间求和。因此,结果必须类似于 总交易时间:1 小时 18 分钟

我试过使用 Carbon,但我不知道如何使用它对 table 的所有行求和。

foreach($timestampStarts as $timestampStart){  
    $time = new Carbon($timestampStart->start_timestamp);
    $shift_end_time =new Carbon($timestampStart->end_timestamp);
    dd($time->diffForHumans($shift_end_time));
}

可以使用MySQLTIMESTAMPDIFF函数计算差值:

Transaction::whereNotNull('_end_timestamp_')
    ->sum(DB::raw('TIMESTAMPDIFF(SECOND, _start_timestamp_, _end_timestamp_)'));

这将以秒为单位为您提供总数。

您需要以分钟为单位检索总差异。添加总差异并检索人类的差异。您可以像下面这样检索:

$diffForHumans = null;
$nowDate = Carbon::now();
$diffInMinutes = 0;

foreach($timestampStarts as $timestampStart){  

    if(!empty($timestampStart->end_timestamp)){ // if the end timestamp is not empty

        $time = new Carbon($timestampStart->start_timestamp);
        $shift_end_time =new Carbon($timestampStart->end_timestamp);

        //Adding difference in minutes
        $diffInMinutes+= $shift_end_time->diffInMinutes($time);
    }
}
$totalDiffForHumans = $now->addMinutes($diffInMinutes)->diffForHumans();