繁体   English   中英

如何在不包括周末的情况下使用 Carbon 获得两个日期之间的分钟差异

[英]How to get diff in minutes between two dates with Carbon excluding weekends

如何在几分钟内获得两个日期之间的差异,但不包括周末(周六和周日)

<?php
require_once __DIR__ . '/autoload.php';

use Carbon\Carbon;
use Carbon\CarbonInterval; 

$created = Carbon::parse("2021-04-11 00:07:13");
$firstResponse = Carbon::parse("2021-04-12 12:35:04");

$diffInMinutes = $created->diffFiltered(CarbonInterval::minute(), function($date){
  return !$date->isWeekend();
}, $firstResponse);

echo $diffInMinutes;

错误消息是Carbon error: Could not find next valid date

谁能帮帮我吗? 谢谢你。

当达到最大循环数( NEXT_MAX_ATTEMPTS = 1000 )时,实际上会发生这种情况,这是由于周末的分钟数而发生的。

虽然您的方法在理论上是正确的,但这将是一种减慢和迭代每分钟数天间隔的方法。

您可以按天计算,直到一天结束,如果不是周末,请添加 diffInMinutes,然后在第二天再做一次。

use Carbon\CarbonImmutable;

$created = CarbonImmutable::parse("2021-04-11 00:07:13");
$firstResponse = CarbonImmutable::parse("2021-04-12 12:35:04");
$diffInMinutes = 0;
$step = $created;

while ($step < $firstResponse) {
    if ($step->isWeekend()) {
        $step = $step->next('Monday');

        continue;
    }

    $nextStep = min($firstResponse, $step->addDay()->startOfDay());

    $diffInMinutes += $step->diffInMinutes($nextStep);
    $step = $nextStep;
}

echo $diffInMinutes;

注意:警告,如果使用Carbon而不是CarbonImmutable你需要替换$step = $created; $step = $created->toImmutable();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM