nthWeekdayInMonth method

Hora? nthWeekdayInMonth(
  1. int weekday,
  2. int n
)

Gets the nth occurrence of a weekday in the current month.

n can be positive (1 = first, 2 = second, etc.) or negative (-1 = last, -2 = second to last, etc.)

Implementation

Hora? nthWeekdayInMonth(int weekday, int n) {
  if (n == 0) return null;

  if (n > 0) {
    var current = firstWeekdayInMonth(weekday);
    for (var i = 1; i < n; i++) {
      current = current.add(7, TemporalUnit.day);
      if (current.month != month) return null;
    }
    return current;
  } else {
    var current = lastWeekdayInMonth(weekday);
    for (var i = -1; i > n; i--) {
      current = current.subtract(7, TemporalUnit.day);
      if (current.month != month) return null;
    }
    return current;
  }
}