Introduction
Java getMonthValue() method is used to get the month value of a date. It returns an integer value that represents the month. This method does not take any argument and returns an integer value.
Import LocalDate class
Import the java.time.LocalDate class in the beginning of the file since it is required to use the getMonthValue() method.
import java.time.LocalDate;
Create a LocalDate object
Create a LocalDate object representing a date of your choice using the of() method. For example, to create a LocalDate object representing February 15, 2015, you would write:
LocalDate localDate = LocalDate.of(2015, 02, 15);
Get the month value
Use the getMonthValue() method to get the month value of the LocalDate object.
int month = localDate.getMonthValue();
Print the month value
Print the month value using the System.out.println() method.
System.out.println("Month of date : "+month);
Compile and run the program
Compile the program using the following command in the terminal:
javac ~/project/YourFileName.java
Run the program using the following command in the terminal:
java YourFileName
Create another LocalDate object
Create another LocalDate object representing a different date of your choice using the ofYearDay() method. For example, to create a LocalDate object representing April 29, 2020, you would write:
LocalDate localDate = LocalDate.ofYearDay(2020, 120);
Get the month value of the new LocalDate object
Use getMonthValue() method to get the month value of the new LocalDate object.
int month = localDate.getMonthValue();
Print the month value
Print the month value using the System.out.println() method.
System.out.println("Month of date : "+month);
Summary
In this lab, you learned how to use the Java getMonthValue() method to get the month value of a date. By following the steps, you created a Java file, imported the necessary class, created a LocalDate object, used the getMonthValue() method to get the month value, printed the month value, compiled and ran the program. You also created another LocalDate object, used the getMonthValue() method to get the month value of the new object, and printed the month value.



