isNthDayOfMonthInRange method

bool isNthDayOfMonthInRange(
  1. int n,
  2. int dayOfWeek,
  3. int month, {
  4. bool inclusive = true,
})

Determines if the nth occurrence of a specific day of the week in a given month falls within the specified date range.

Implementation

bool isNthDayOfMonthInRange(int n, int dayOfWeek, int month, {bool inclusive = true}) {
  // Check if the month is even within the range's months
  if (month < start.month || month > end.month) {
    return false;
  }

  // Iterate through each year within the range
  for (int year = start.year; year <= end.year; year++) {
    // Optimization: Only proceed if the month is within the range for the
    // current year
    if ((year == start.year && month < start.month) || (year == end.year && month > end.month)) {
      continue;
    }

    // Use getNthWeekdayOfMonthInYear to get the date
    final DateTime? nthOccurrence = DateTime(
      year,
      month,
    ).getNthWeekdayOfMonthInYear(n, dayOfWeek);

    // Crucial Check: Ensure the nth occurrence is within the target month
    if (nthOccurrence == null || nthOccurrence.month != month) {
      continue;
    }

    // Check if the nth occurrence is in
    // Check if the nth occurrence is in range
    if (inclusive) {
      if ((nthOccurrence.isAtSameMomentAs(start) || nthOccurrence.isAfter(start)) &&
          (nthOccurrence.isAtSameMomentAs(end) || nthOccurrence.isBefore(end))) {
        return true;
      }
    } else {
      if (nthOccurrence.isAfter(start) && nthOccurrence.isBefore(end)) {
        return true;
      }
    }
  }

  // If we couldn't find the nth occurrence in any year within the range,
  //  return false
  return false;
}