Java program to adjust LocalDate to first day of month with TemporalAdjusters class



In this article, we will learn how to adjust a LocalDate object to find the first day of the month in Java. The program demonstrates how to take a given date and use the TemporalAdjusters class to easily get the first day of that month. This functionality is useful in various applications, such as scheduling events or generating monthly reports

TemporalAdjusters provides utility methods for common date adjustments. We will learn how to set a specific date and adjust it to find the first day of the month.

Problem Statement

Write a Java program that adjusts a LocalDate to find and display the first day of the month based on a given date ?

Input

Current Date = 2019-04-10

Output

Current Date = 2019-04-10
Current Month = APRIL
First day of month = 2019-04-01

Steps to adjust LocalDate to first day of month

Following are the steps to adjust LocalDate to first day of month ?

  • First, we will import the necessary classes from java.time package.
  • We will create a LocalDate instance by setting up a specific date using LocalDate.of().
  • After that, we will display the current date by printing the current date to the console.
  • Get the current month and extract and print the month from the LocalDate.
  • Adjust to the first day of the month.
  • At last, print the first day of the month to the console.

Java program to adjust LocalDate to first day of month

Below is the Java program to adjust LocalDate to the first day of the month ?

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
public class Demo {
   public static void main(String[] args) {
      LocalDate localDate = LocalDate.of(2019, Month.APRIL, 10);
      System.out.println("Current Date = "+localDate);
      System.out.println("Current Month = "+localDate.getMonth());
      LocalDate day = localDate.with(TemporalAdjusters.firstDayOfMonth());
      System.out.println("First day of month = "+day);
   }
}

Output

Current Date = 2019-04-10
Current Month = APRIL
First day of month = 2019-04-01

Code explanation

The program begins by importing necessary classes from the java.time package. A LocalDate object is created with the date set to April 10, 2019. The current date is printed to the console, followed by the current month extracted using getMonth(). The program then adjusts the date to the first day of the month using the firstDayOfMonth() method from the TemporalAdjusters class. Finally, it prints the adjusted date, which is the first day of April 2019.

Updated on: 2024-09-29T02:47:31+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements