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.
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.
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 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);
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 value of the dayOfMonth variable to the console using System.out.println().
System.out.println("Day of the month: " + dayOfMonth);
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 parsedDate object using the getDayOfMonth() method and assign the result to a variable.
int parsedDayOfMonth = parsedDate.getDayOfMonth();
Print the value of parsedDayOfMonth to the console using System.out.println().
System.out.println("Day of the month (parsed): " + parsedDayOfMonth);
Compile the program using the following command:
javac LocalDateDemo.java
Run the program using the following command:
java LocalDateDemo
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.