I want to calculate the number of working days.
By using carbon I can calculate days and reduce weekends.
$num_days = $to_date->diffInWeekdays($from_date) + 1;
And I have an array of holidays, and I want to reduce the number of days if there is a holiday in between the days.
Is there any way to do this.
Thank you
The NETWORKDAYS Function[1] calculates the number of workdays between two dates in Excel. When using the function, the number of weekends are automatically excluded. It also allows you to skip specified holidays and only count business days. It is categorized in Excel as a Date/Time Function.
You could use diffInDaysFiltered
to achieve what you're after.
Assuming your holidays are an array of Carbon
instances you could do something like:
$start = Carbon::now()->setDate(2014, 1, 1);
$end = Carbon::now()->setDate(2015, 1, 1);
$holidays = [
Carbon::create(2014, 2, 2),
Carbon::create(2014, 4, 17),
Carbon::create(2014, 5, 19),
Carbon::create(2014, 7, 3),
];
$days = $start->diffInDaysFiltered(function (Carbon $date) use ($holidays) {
return $date->isWeekday() && !in_array($date, $holidays);
}, $end);
If it's just an array of strings then you could do something like:
!in_array($date->format('[the-format-of-your-dates]'), $holidays)
Hope this helps!
Here is a small utility function to calculate working days:
function getWorkingDaysCount($from, $to) {
$workingDays = [1, 2, 3, 4, 5]; // Working days (week days)
$holidayDays = ['*-12-25', '*-01-01']; // Holidays array, add desired dates to this array
$from = new DateTime($from);
$to = new DateTime($to);
$to->modify('+1 day');
$interval = new DateInterval('P1D');
$periods = new DatePeriod($from, $interval, $to);
$days = 0;
foreach ($periods as $period) {
if (!in_array($period->format('N'), $workingDays)) continue;
if (in_array($period->format('Y-m-d'), $holidayDays)) continue;
if (in_array($period->format('*-m-d'), $holidayDays)) continue;
$days++;
}
return $days;
}
You can pass the starting and end date to get the number of days.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With