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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024