使用 Carbon 从 Array 求和时间

Sum times from Array using Carbon

如何使用 Carbon 将时间求和到数组中?

<?php
namespace App\Models;
use Carbon\Carbon;
class Appointment extends BaseModel 
{
  public static function total_time()
  {
    $appointments = Appointment::get();
    $sumtimes = [];
    foreach($appointments as $a){
        $dti = Carbon::parse($a->dateinitial);
        $dtf = Carbon::parse($a->datefinal);
        $time = $dti->diff($dtf)->format('%H:%I:%S');
        $sumtimes[] = $time;
    }
    $sumtimes= sum($sumtimes);
    return $sumtimes;

}

在sum_times里面,有一个时间列表需要总结如下:

$sum_times[0] = "00:01:18"
$sum_times[1] = "00:03:11"
$sum_times[2] = "01:01:18"
$sum_times[3] = "00:01:28"

我需要它return“01:07:15”

<?php

public static function total_time(): string
{
    $seconds = 0;

    foreach(Appointment::get() as $appointment){
        $dateinitial = Carbon::parse($appointment->dateinitial);
        $datefinal = Carbon::parse($appointment->datefinal);
        $seconds += $datefinal->diffInSeconds($dateinitial);
    }

    return gmdate('H:i:s', $seconds);
}

您还必须为您的字段设置 (dateinitial, datefinal) 将自动解析的日期时间转换为 Carbon 类型。 Docs for date casts.

diff的每一个结果都可以连续添加到一个datum中。在循环结束时,我们得到总和作为基准日期与日期的差值。 Carbon 是 DateTime 的扩展。我展示了带有基础 class 的示例代码,以便每个人都可以重现它。

$data = [
  ['from' => '2022-03-01 16:00', 'to' => '2022-03-02 12:00'],  //20:00:00
  ['from' => '2022-03-02 12:30', 'to' => '2022-03-02 22:02'],  //09:32:00
];  //total 29:32:00

$basis = '2000-01-01';
$dateBase = date_create('2000-01-01');
$date = clone $dateBase;

foreach($data as $dates){
  $dateFrom = date_create($dates['from']);
  $dateTo = date_create($dates['to']);
  $diff = $dateFrom->diff($dateTo);
  $date->add($diff);
}
$totalDiff = $dateBase->diff($date);
$hours = $totalDiff->d *24 + $totalDiff->h;  //days * 24 + hours

echo 'Sum: '.$hours.$totalDiff->format(':%I:%S');
//Sum: 29:32:00

3v4l.org

上试试自己