
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.