getNthWeekdayOfMonthInYear method
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).
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
DateTime? getNthWeekdayOfMonthInYear(int n, int dayOfWeek) {
if (n < 1) {
return null;
}
final int firstWeekday = DateTime(year, month).weekday;
final int offset =
(dayOfWeek - firstWeekday + DateConstants.daysPerWeek) % DateConstants.daysPerWeek;
// Compute the target day-of-month directly and let DateTime normalize any
// overflow into the next month (caught by the month check below). Calendar
// fields, NOT `add(Duration(days: ...))`: a fixed-day Duration step on a
// LOCAL DateTime drifts off midnight across a DST boundary and a fall-back
// (25h) day can push the result back onto the previous calendar day.
final int targetDay = 1 + offset + (n - 1) * DateConstants.daysPerWeek;
final DateTime nthOccurrence = DateTime(year, month, targetDay);
if (nthOccurrence.month != month) {
return null;
}
return nthOccurrence;
}