dayOfWeekInMonth()
is a handy method in java.time.temporal.TemporalAdjusters
class that returns an adjuster which changes the date to the n-th day of week in the current month.
Here is an example of how you could use it:
package org.kodejava.datetime;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class DayOfWeekInMonthExample {
public static void main(String[] args) {
// Current date
LocalDate date = LocalDate.now();
// The 2nd Tuesday in the month of the date.
LocalDate secondTuesday = date.with(
TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));
System.out.println("Current Date: " + date);
System.out.println("Second Tuesday: " + secondTuesday);
}
}
Output:
Current Date: 2024-01-18
Second Tuesday: 2024-01-09
This code would display the date of the second Tuesday in the current month.
Here’s what’s going on in this case:
TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY)
specifies that we want the second occurrence ofDayOfWeek.TUESDAY
in the current month.-
date.with(TemporalAdjuster)
modifies the LocalDate date based on theTemporalAdjuster
that is passed in. The original date object is unchanged; a newLocalDate
reflecting the adjusted date is returned.
This TemporalAdjusters
method is very useful when you have conditional logic based on things like “if it’s the third Monday of the month, then…”
Latest posts by Wayan (see all)
- How do I secure servlets with declarative security in web.xml - April 24, 2025
- How do I handle file uploads using Jakarta Servlet 6.0+? - April 23, 2025
- How do I serve static files through a Jakarta Servlet? - April 23, 2025