How do I use firstInMonth() and lastInMonth() method of TemporalAdjusters class?

TemporalAdjusters.firstInMonth(DayOfWeek)

and TemporalAdjusters.lastInMonth(DayOfWeek) methods are part of the java.time.temporal.TemporalAdjusters class. They adjust the date to the first or last occurrence of the specified DayOfWeek in the month.

Here’s an example of how to use these methods:

package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public class FirstLastInMonthExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();
        System.out.println("Current date: " + date);

        LocalDate firstMondayInMonth = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println("First Monday of this month: " + firstMondayInMonth);

        LocalDate lastFridayInMonth = date.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
        System.out.println("Last Friday of this month: " + lastFridayInMonth);
    }
}

The output of the code snippet above:

Current date: 2024-01-18
First Monday of this month: 2024-01-01
Last Friday of this month: 2024-01-26

In this example:

  • LocalDate.now()` is used to get the current date.
  • .with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)) adjusts the date to the first Monday of the current month.
  • .with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)) adjusts the date to the last Friday of the current month.
Wayan

Leave a Reply

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