Introduction
Java's LocalDate class has several methods that help in getting information about the date. One such method is the getMonth() method which is used to get the month of a date. In this lab, you will learn how to use the getMonth() method.
Set up the project directory
First, create a project directory in the terminal as follows:
mkdir project
Create a Java file
Create a new Java file in the directory you just created as follows:
touch project/DateDemo.java
Import required classes
To use the LocalDate and Month classes, you need to import them at the top of the Java file as follows:
import java.time.LocalDate;
import java.time.Month;
Create a LocalDate object
Next, create a LocalDate object using the of() method. This object represents the date for which you want to get the month. In this example, we will use the date 2022/10/31.
LocalDate localDate = LocalDate.of(2022, 10, 31);
Call the getMonth() method
Call the getMonth() method on the LocalDate object to get the month of the date.
Month month = localDate.getMonth();
Output the result
Print the month using the System.out.println() method.
System.out.println("Month of date : " + month);
Compile and run the program
Save the file and compile the program using the following command in the terminal:
javac project/DateDemo.java
Then, run the program using the following command:
java -cp project DateDemo
Viewing the output
The program will output the following:
Month of date : OCTOBER
Summary
In this lab, you learned how to use the getMonth() method of the LocalDate class in Java to get the month of a date. You also learned how to create LocalDate objects and output the month obtained from the getMonth() method. This method is useful when you need to extract information from a date or when you want to display the month of a date in a user-friendly way.



