Search code examples
phpphp-carbon

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.


Solution

  • 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();