Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate working days between to dates

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

like image 957
Muhsin VeeVees Avatar asked Jan 04 '17 11:01

Muhsin VeeVees


People also ask

How do I calculate working days between two dates in Excel?

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.


2 Answers

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!

like image 121
Rwd Avatar answered Oct 12 '22 00:10

Rwd


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.

like image 44
Thamilhan Avatar answered Oct 11 '22 22:10

Thamilhan