getWorkdayNumberInMonth static method

int getWorkdayNumberInMonth(
  1. DateTime date, {
  2. bool shouldThrow = false,
})

Returns the workday number in the month of the date.

Throws if shouldThrow is true and date is not a workday (weekend: saturday or sunday). If shouldThrow is false and date is not a workday (weekend: saturday or sunday), returns 0.

Implementation

static int getWorkdayNumberInMonth(
  DateTime date, {
  bool shouldThrow = false,
}) {
  const workdays = EveryWeekday.workdays;
  if (workdays.invalid(date)) {
    if (shouldThrow) {
      throw ArgumentError.value(
        date,
        'date',
        'Must be a workday. Workdays: '
            '${workdays.map((e) => e.weekday.name).join(', ')}',
      );
    }
    return 0;
  }
  var local = date.copyWith();
  var workdaysCount = 0;
  while (local.isAtSameMonthAs(date)) {
    if (workdays.valid(local)) workdaysCount++;
    local = workdays.previous(local);
  }
  return workdaysCount;
}