简体   繁体   中英

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

how do I get diff between two dates in minutes, but excluding the weekend (Saturday & Sunday)

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

The error message was Carbon error: Could not find next valid date

Can anyone please help me? thank you.

This actually happens when the maximum number of loops is reached ( NEXT_MAX_ATTEMPTS = 1000 ) which happens here due to the number of minutes in the week-end.

While your approach is theorically correct, it would be way to slow and to iterate over each minute for intervals of multiple days.

You could rather calculate on a day basis, diff until end of day, add diffInMinutes if it's not the week-end then do it again on the next day.

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;

Note: warning, if using Carbon instead of CarbonImmutable you'll need to replace $step = $created; with $step = $created->toImmutable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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