getNthWeekdayOfMonthInYear method

  1. @useResult
DateTime? getNthWeekdayOfMonthInYear(
  1. int n,
  2. int dayOfWeek
)

Returns the date of the nth occurrence of dayOfWeek within the current instance's month and year, or null if it does not exist (e.g., 5th Friday in February).

n is the desired occurrence (e.g., 1 for the 1st, 2 for the 2nd). dayOfWeek is the day of the week (e.g., DateTime.monday).

Implementation

@useResult
DateTime? getNthWeekdayOfMonthInYear(int n, int dayOfWeek) {
  if (n < 1) {
    return null;
  }

  final DateTime firstDayOfMonth = DateTime(year, month);

  final int offset =
      (dayOfWeek - firstDayOfMonth.weekday + DateConstants.daysPerWeek) %
      DateConstants.daysPerWeek;

  final DateTime firstOccurrence = firstDayOfMonth.add(Duration(days: offset));

  final DateTime nthOccurrence = firstOccurrence.add(
    Duration(days: (n - 1) * DateConstants.daysPerWeek),
  );
  if (nthOccurrence.month != month) {
    return null;
  }

  return DateTime(
    nthOccurrence.year,
    nthOccurrence.month,
    nthOccurrence.day,
  );
}