Introduction
The java.time.LocalDate class represents a date without a time zone component, such as 2022-05-26. The getDayOfMonth() method is used to get the day of a month from a LocalDate object.
Import LocalDate class
In order to use the LocalDate class and its getDayOfMonth() method, we need to import the java.time.LocalDate package.
import java.time.LocalDate;
Create a LocalDate object
Create a new LocalDate object using one of the available constructors. For example, create the LocalDate for May 26, 2022.
LocalDate localDate = LocalDate.of(2022, 5, 26);
Get the day of the month from the LocalDate object
Call the getDayOfMonth() method to get the day of the LocalDate object and assign the result to an integer variable.
int dayOfMonth = localDate.getDayOfMonth();
Print the day of the month
Print the value of the dayOfMonth variable to the console using System.out.println().
System.out.println("Day of the month: " + dayOfMonth);
Parse a date from a string
We can parse a date from a string using the parse() method of LocalDate. For example, parse the date "2022-05-26" and assign it to a LocalDate object.
LocalDate parsedDate = LocalDate.parse("2022-05-26");
Get the day of the month from the parsed LocalDate object
Get the day of the parsedDate object using the getDayOfMonth() method and assign the result to a variable.
int parsedDayOfMonth = parsedDate.getDayOfMonth();
Print the day of the month from the parsed LocalDate object
Print the value of parsedDayOfMonth to the console using System.out.println().
System.out.println("Day of the month (parsed): " + parsedDayOfMonth);
Compile and run the program
Compile the program using the following command:
javac LocalDateDemo.java
Run the program using the following command:
java LocalDateDemo
Summary
In this lab, you learned how to use the getDayOfMonth() method of the LocalDate class in Java. You learned how to create a LocalDate object, get the day of the month from the object, and parse a date from a string. You also learned how to compile and run a Java program in the terminal.



