Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

guianzollin's avatar

How to add days excluding weekends and custom dates

This approach worked for me, does anyone see any issues or have a better approach?

$daysToAdd = 10;

$holidays = ["2023-04-19", "2023-04-20", "2023-04-21"];

$date = today();

for ($i = 0; $i < $daysToAdd; $i++) {

  $date->addDay();

  while ($date->isWeekend()) {
    $date->addDay();
  }

  while (in_array($date->toDateString(), $holidays)) {
    $date->addDays($date->isFriday() ? 3 : 1);
  }
}

echo $date;
0 likes
9 replies
Snapey's avatar

@guianzollin something like this. (only quickly checked)

use Carbon\Carbon;
$start = today();
$end = new Carbon('2023-04-28');
$known= collect(['2023-04-17', '2023-04-22', '2023-05-01']);

// gets the diff in days unless the date is a weekend
$days = $start->diffInDaysFiltered(function(Carbon $date) {
    return !($date->isSunday() || $date->isSaturday());
}, $end);

// exclude known dates from calculation between start and end unless they are weekend in which case already allowed for

$exclude = $known->reject(function($date) use($start, $end){
  $date = Carbon::parse($date);
  if($date->isSunday() || $date->isSaturday()) {
    return true;
  }
  return ($date < $start || $date >$end);
})->count();

$totaldays = $days - $exclude;

Snapey's avatar

Sorry, this tells you the difference in days. You want to add days but not weekend or known dates. I could probably refactor after I have slept

Snapey's avatar

you can addWeekdays(10) and then add a day for each holiday between start and end

guianzollin's avatar

@Snapey in this approach the last days added can be a holiday, which is a problem.

The code I suggested worked, do you see any problems with it?

Thanks for the feedback!

psrz's avatar

Does this mean add X number of "workable" days ?

    $daysToAdd = 10;
    $holidays = ["2023-04-19", "2023-04-20", "2023-04-21"];
    $days = [];
    $date = CarbonImmutable::make(today());
    $i = 1;

    while($i <= $daysToAdd) {
        if ($date->isWeekend() or in_array($date->format('Y-m-d'), $holidays)) {
            $date = $date->addDay();
            continue;
        }
        $days[] = $date;
        $date = $date->addDay();
        $i++;
    }
    
    dd($days);

That should work.

guianzollin's avatar

@psrz yep, your approach worked too!

Do you see any issues in my approach?

Please or to participate in this conversation.