Laravel

Business Days Calculator 💡

class BusinessDaysCalculator
{
    private $holidays;

    public function __construct(array $holidays = [])
    {
        $this->holidays = collect($holidays)->map(function ($date) {
            return Carbon::parse($date)->format('Y-m-d');
        });
    }

    public function calculateBusinessDays(Carbon $startDate, Carbon $endDate): int
    {
        $period = CarbonPeriod::create($startDate, $endDate);
        
        return $period->filter(function (Carbon $date) {
            return !$this->isWeekend($date) && !$this->isHoliday($date);
        })->count();
    }

    public function addBusinessDays(Carbon $startDate, int $days): Carbon
    {
        $date = $startDate->copy();
        $businessDays = 0;

        while ($businessDays < $days) {
            $date->addDay();
            if (!$this->isWeekend($date) && !$this->isHoliday($date)) {
                $businessDays++;
            }
        }

        return $date;
    }

    private function isWeekend(Carbon $date): bool
    {
        return $date->isWeekend();
    }

    private function isHoliday(Carbon $date): bool
    {
        return $this->holidays->contains($date->format('Y-m-d'));
    }
}