Warm tip: This article is reproduced from stackoverflow.com, please click
laravel php-carbon

Best way to sum time in Laravel?

发布于 2020-03-27 10:30:21

I have a table called transactions with two relevant fields to my question, _start_timestamp_ and _end_timestamp_. I need to sum the amount of time passed between all transactions where _end_timestamp_ is not null. So, the result must be something like Total Time of Transactions: 1 hour and 18 minutes

I've tried using Carbon, but I don't know how to sum all the lines of the table using it.

foreach($timestampStarts as $timestampStart){  
    $time = new Carbon($timestampStart->start_timestamp);
    $shift_end_time =new Carbon($timestampStart->end_timestamp);
    dd($time->diffForHumans($shift_end_time));
}
Questioner
Bruno Albuquerque
Viewed
191
Chin Leung 2019-07-04 00:07

You can use the MySQL TIMESTAMPDIFF function to calculate the difference:

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

This will give you the total in seconds.