nthWeekdayOf function

DateTime? nthWeekdayOf(
  1. int year,
  2. int month,
  3. int n,
  4. int weekday, {
  5. bool utc = false,
})

The nth weekday of month/year; negative n counts from the end.

Implementation

DateTime? nthWeekdayOf(int year, int month, int n, int weekday, {bool utc = false}) {
  if (n == 0) return null;
  final dim = daysInMonth(year, month);
  if (n > 0) {
    final first = DateTime.utc(year, month).weekday;
    final day = 1 + (weekday - first + 7) % 7 + (n - 1) * 7;
    if (day > dim) return null;
    return utc ? DateTime.utc(year, month, day) : DateTime(year, month, day);
  }
  final last = DateTime.utc(year, month, dim).weekday;
  final day = dim - (last - weekday + 7) % 7 + (n + 1) * 7;
  if (day < 1) return null;
  return utc ? DateTime.utc(year, month, day) : DateTime(year, month, day);
}