lastWeekdayOfMonth static method

  1. @useResult
DateTime lastWeekdayOfMonth(
  1. int year,
  2. int month,
  3. int weekday
)

Returns the last weekday in month of year — always a real date, since every weekday occurs at least four times a month.

month is 1..12 and weekday is a DateTime weekday constant (1 = Monday .. 7 = Sunday).

Example:

// Last Sunday of October 2026 (EU daylight-saving end).
MonthWeekdayUtils.lastWeekdayOfMonth(2026, 10, DateTime.sunday);

Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
static DateTime lastWeekdayOfMonth(int year, int month, int weekday) {
  // Day 0 of the NEXT month is the last day of THIS month (handles 28/29/30/31
  // and the December roll-over, where month + 1 = 13 normalizes to January).
  final DateTime lastDayOfMonth = DateTime(year, month + 1).subtract(_oneDay);

  // Step back to the most recent matching weekday. The +7 keeps the modulus
  // non-negative when the month ends earlier in the week than [weekday].
  final int daysToSubtract =
      (lastDayOfMonth.weekday - weekday + DateConstants.daysPerWeek) % DateConstants.daysPerWeek;

  return lastDayOfMonth.subtract(Duration(days: daysToSubtract));
}