【问题标题】:How to get diff in minutes between two dates with Carbon excluding weekends如何在不包括周末的情况下使用 Carbon 获得两个日期之间的分钟差异
【发布时间】:2021-04-15 04:48:46
【问题描述】:

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

<?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

谁能帮帮我?谢谢。

【问题讨论】:

    标签: php php-carbon


    【解决方案1】:

    这实际上发生在达到最大循环数 (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-&gt;toImmutable();

    【讨论】:

    • 你是巫师吗? ;)
    • 我维护Carbon 库,我想这会有所帮助^^
    猜你喜欢
    • 2021-10-16
    • 1970-01-01
    • 2019-12-10
    • 2018-02-06
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    相关资源
    最近更新 更多