dayOfWeekInMonth: Nth Occurrence of a Day
You'll learn how to find the nth occurrence of a specific day-of-week within a month, like "the second Tuesday" or "the fourth Friday."
The Challenge
Sometimes you need dates defined not by a fixed day number, but by their position among weekdays: "the third Monday of next month" for a meeting series, or "the last Friday" for payroll. The dayOfWeekInMonth adjuster solves this elegantly.
The Core Concept
TemporalAdjusters.dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek) returns an adjuster that finds the nth occurrence of a day-of-week in a month. You provide two arguments:
- ordinal: Which occurrence (1 for first, 2 for second, etc.; negative values count from month-end)
- dayOfWeek: The target day (like
DayOfWeek.MONDAY)
Think of it like navigating a calendar grid: "Start at the top, count down three rows of Mondays, land there."
How It Works
LocalDate date = LocalDate.of(2024, 3, 15); // Some day in March
// Find the 2nd Wednesday in March
LocalDate secondWed = date.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.WEDNESDAY));
// Find the 3rd Friday in March
LocalDate thirdFri = date.with(TemporalAdjusters.dayOfWeekInMonth(3, DayOfWeek.FRIDAY));
// Find the last Monday (-1 means last occurrence)
LocalDate lastMon = date.with(TemporalAdjusters.dayOfWeekInMonth(-1, DayOfWeek.MONDAY));
The adjuster works within the current month of the date you apply it to, replacing the day component to match your criteria.
Practical Applications
Use this for recurring schedules: board meetings on the first Monday, paychecks on the second and fourth Fridays, or monthly reports due the last business day (combining with day-of-week logic).
Key Takeaway: TemporalAdjusters.dayOfWeekInMonth(ordinal, dayOfWeek) finds the nth occurrence of any weekday within a month, with positive numbers counting from the start and negative from the end.