PHP-碳日期时间DiffInSeconds以及如何按小时分组

时间:2017-06-24 13:05:34

标签: php laravel datetime laravel-5 php-carbon

我计算2个日期时间之间的差异,但是我希望按小时对它们进行分组。它应该是那样的。

这就是我在2个日期之间获得差异的方式。

$date_diff = $first->created_at->diffInSeconds($second->created_at);

例如,第一次是09:47:20,下一次是11:47:50我需要按小时这样的小组。

In 09:00 =  12.40 Minutes
In 10:00 =  60.00 Minutes
In 11:00 =  47.50 Minutes

我该怎么做?你会对此提出什么建议?

由于

1 个答案:

答案 0 :(得分:0)

您可以查看以下代码。

请记住,如果开始时间<=结束时间,它会按预期工作。

此外,还有改进的余地,比如提取逻辑来分离函数或在需要的地方添加尾随/前导零,但它应该让你开始。

    $start = '09:47:20';
    $end = '11:47:50';

    $startTime = Carbon::createFromFormat('H:i:s', $start);
    $endTime = Carbon::createFromFormat('H:i:s', $end);

    $startHour = $startTime->hour; // 9
    $endHour = $endTime->hour; // 11

    $hourRange = range($startHour, $endHour); // array(9, 10, 11)

    if (count($hourRange) === 1) {
        // start and end time share the same hour
        $hourRange = array($startHour, $endHour);
    }

    $lastIndex = count($hourRange) - 1;
    $diffGrouped = array();

    foreach ($hourRange as $index => $hour) {

        if ($index === 0) {

            // start hour has the next full hour - calculate the difference
            $nextFullHour = $startHour + 1;
            $nextFullHourTime = Carbon::createFromFormat('H', $nextFullHour);

            $minutes = $startTime->diff($nextFullHourTime)->format('%i.%s');

        } else if ($index === $lastIndex) {

            // end hour is its own "previous full hour"
            $previousFullHourTime = Carbon::createFromFormat('H', $endHour);

            $minutes = $endTime->diff($previousFullHourTime)->format('%i.%s');

        } else {

            // everything between the start and the end hour
            $minutes = '60.00';

        }

        $diffGrouped[] = array(
            'hour' => $hour,
            'minutes' => $minutes
        );

    }

    dd($diffGrouped);

    /*
     array:3 [
          0 => array:2 [
            "hour" => 9
            "minutes" => "12.40"
          ]
          1 => array:2 [
            "hour" => 10
            "minutes" => "60.00"
          ]
          2 => array:2 [
            "hour" => 11
            "minutes" => "47.50"
          ]
        ]
    */