Laravel Carbon | Add number of days excluding weekends and custom dates

--

First You can Check your project weekend days

Carbon::getWeekendDays()

In your App/Providers/AppServiceProvider.php you can add in boot method :

Carbon::setWeekStartsAt(Carbon::FRIDAY);
Carbon::setWeekEndsAt(Carbon::THURSDAY);

You can also change Week-end if needed :

Carbon::setWeekendDays([
Carbon::SUNDAY,
Carbon::MONDAY,
]);

Code

use Carbon\Carbon;if (!function_exists('get_date_using_weekend_count')) {
function get_date_using_weekend_count($date,$count,$holidays)
{
$MyDateCarbon = Carbon::parse($date);
$MyDateCarbon->addWeekdays($count);
for ($i = 1; $i <= $count; $i++) {
if (in_array(Carbon::parse($date)->addWeekdays($i)->toDateString(), $holidays)) {
$MyDateCarbon->addDay();
}
}
return $MyDateCarbon->toFormattedDateString();
}
}

Function Can be Used Like Below

$holidays = ["2015-01-01", "2015-01-02"];$count = 25;$date = "2022-09-20";dd(get_date_using_weekend_count($date,$count,$holidays));

Output

Oct 25, 2022

So basically it adds $count Weekdays and checks if any of the Weekdays added is a holiday and if there are any, it’ll add a day to the final date. Thanks! Couldn’t have thought of it without you.

--

--