Introduction
In this lab, you will learn about the range() method of the Java LocalDate class. This method is used to get the range of valid values for a specified date field, such as the day-of-month, day-of-week, or year. You will learn how to use ChronoField enum as an argument to get a range of the specified field.
Import necessary classes
To use the LocalDate class and ChronoField enum, you need to import them at the beginning of your code file.
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
Create a LocalDate object
We will create a LocalDate object for any date, such as 2022-01-01.
LocalDate date = LocalDate.of(2022, 01, 01);
Get the range of the day-of-month field
Now, we will get the range of the day-of-month field using the range() method and the ChronoField.DAY_OF_MONTH constant.
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Print the range of valid values
We will print the range of valid values for the day-of-month field using the getValue() method of ValueRange.
System.out.println("Range of valid values for day-of-month: " + range);
Get the range of the month field
Now, we will get the range of the month field using the range() method and the ChronoField.MONTH_OF_YEAR constant.
ValueRange range2 = date.range(ChronoField.MONTH_OF_YEAR);
Print the range of valid values
We will print the range of valid values for the month field using the getValue() method of ValueRange.
System.out.println("Range of valid values for month: " + range2);
Get the range of the year field
Now, we will get the range of the year field using the range() method and the ChronoField.YEAR constant.
ValueRange range3 = date.range(ChronoField.YEAR);
Print the range of valid values
We will print the range of valid values for the year field using the getValue() method of ValueRange.
System.out.println("Range of valid values for year: " + range3);
Compile and run the program
To compile and run the program, type the following commands in the terminal:
javac LocalDateRange.java
java LocalDateRange
If everything is correct, you will see the range of valid values for the day-of-month, month, and year fields.
Summary
Congratulations! You have learned how to use the range() method of the Java LocalDate class to get the range of valid values for a specified date field. You learned how to use the ChronoField enum as an argument to get the range of the specified field.



