How do I use TemporalAdjusters firstDayOfMonth() method?

The TemporalAdjusters.firstDayOfMonth() method in Java is used to obtain a copy of the current date with the day set to the first day of the current month.

This method is quite simple to use. You need to import the java.time package and use the with() function in conjunction with TemporalAdjusters.firstDayOfMonth().

Here’s a simple example in Java:

package org.kodejava.datetime;

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

public class FirstDayOfMonthExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate date = LocalDate.now();

        // Adjust to first day of current month
        LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth());

        System.out.println("Current date: " + date);
        System.out.println("First day of this month: " + firstDayOfMonth);
    }
}

Output:

Current date: 2024-01-18
First day of this month: 2024-01-01

In this example, LocalDate.now() is used to get the current date. Then .with(TemporalAdjusters.firstDayOfMonth()) is used to adjust the date to the first day of the current month.

Wayan

Leave a Reply

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