How do I use TemporalAdjusters dayOfWeekInMonth() method?

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 of DayOfWeek.TUESDAY in the current month.
  • date.with(TemporalAdjuster) modifies the LocalDate date based on the TemporalAdjuster that is passed in. The original date object is unchanged; a new LocalDate 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…”

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.