nthWeekdayOfMonth static method
Returns the nth weekday in month of year, or null when that
occurrence does not exist (e.g. a 5th Friday in a month with only four).
n is 1-based (1 = first). month is 1..12 and weekday is a
DateTime weekday constant (1 = Monday .. 7 = Sunday). Out-of-range n,
month, or weekday returns null rather than silently computing a
neighboring month — these statics take untrusted calendar input, so an
invalid argument must not produce a plausible-but-wrong date.
Example:
// 2nd Sunday of March 2026 (US daylight-saving start).
MonthWeekdayUtils.nthWeekdayOfMonth(2026, 3, 2, DateTime.sunday);
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
static DateTime? nthWeekdayOfMonth(int year, int month, int n, int weekday) {
// Guard explicitly: DateTime(year, month) would normalize an out-of-range
// month into a different one, so the underlying extension's own
// month-mismatch check could not catch it. Reject up front instead.
if (n < 1 ||
month < DateConstants.minMonth ||
month > DateConstants.maxMonth ||
weekday < DateTime.monday ||
weekday > DateTime.sunday) {
return null;
}
// Reuse the instance algorithm with a seed date for the requested month.
return DateTime(year, month).getNthWeekdayOfMonthInYear(n, weekday);
}