Course contentsShow
← Java
Lesson 1880 of 2,87038. Date and Time API (java.time)Free lesson

Ordinal Day Adjusters: firstInMonth and lastInMonth

Finding the first or last occurrence of a day-of-week within a month, like the last Friday.

Ordinal Day Adjusters: firstInMonth and lastInMonth

What you'll learn: How to find the first or last occurrence of a specific day-of-week within any month using temporal adjusters.

The Problem They Solve

Sometimes you need to find dates like "the first Monday in March" or "the last Friday in December." These aren't fixed dates—they change depending on how the month's days fall. The TemporalAdjusters class provides firstInMonth() and lastInMonth() methods specifically for these scenarios.

How They Work

Both methods take a DayOfWeek parameter and return a TemporalAdjuster that finds the specified day within the current month.

firstInMonth(DayOfWeek) adjusts any date to the first occurrence of that day-of-week in the same month.

lastInMonth(DayOfWeek) adjusts any date to the last occurrence of that day-of-week in the same month.

LocalDate someDay = LocalDate.of(2024, 3, 15); // Mid-March

// Find the first Friday in March 2024
LocalDate firstFriday = someDay.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY));
// Result: 2024-03-01 (if March 1st is a Friday, otherwise next Friday)

// Find the last Friday in March 2024
LocalDate lastFriday = someDay.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
// Result: 2024-03-29

Practical Use Cases

These adjusters are perfect for:

  • Scheduling monthly meetings ("first Tuesday of every month")
  • Payroll processing ("last working Friday")
  • Event planning ("last Sunday for monthly gatherings")
LocalDate today = LocalDate.now();
LocalDate nextMonthlyMeeting = today.with(TemporalAdjusters.firstInMonth(DayOfWeek.TUESDAY));

Key Takeaway: Use TemporalAdjusters.firstInMonth() and lastInMonth() with a DayOfWeek to quickly find the first or last occurrence of any weekday within a month—perfect for recurring events and scheduling logic.