Java LocalDate isSupported Method

JavaJavaBeginner
Practice Now

Introduction

The isSupported() method is part of the java.time.LocalDate class in Java. It can be used to check whether a specified field is supported by a LocalDate object or not. This method takes one argument of the type java.time.temporal.TemporalField and returns a boolean value.

Create a new Java file

In this step, you will create a new Java file in the ~/project directory. Open your terminal and execute the following command:

touch ~/project/LocalDateDemo.java

Import necessary classes

In order to use LocalDate and ChronoField classes, you need to import them into your Java file. Copy the following code and paste it at the beginning of LocalDateDemo.java file.

import java.time.LocalDate;
import java.time.temporal.ChronoField;

Create a LocalDate object

In this step, you will create a LocalDate object that represents a specific date. Replace the existing code in main() method with the following:

public static void main(String[] args) {
    LocalDate date = LocalDate.of(2022, 5, 20);
    System.out.println("Date: " + date);
}

This will create a LocalDate object with the date May 20, 2022.

Check if a field is supported

In this step, you will use the isSupported() method to check if the MONTH_OF_YEAR field is supported by the LocalDate object. Add the following code after the creation of the LocalDate object:

boolean isMonthSupported = date.isSupported(ChronoField.MONTH_OF_YEAR);
System.out.println("Is Month of year supported: " + isMonthSupported);

This will check if MONTH_OF_YEAR is supported by the LocalDate object and print the result.

Check for unsupported field

In this step, you will check for an unsupported field. Add the following code after the previous step:

boolean isHourSupported = date.isSupported(ChronoField.HOUR_OF_DAY);
System.out.println("Is Hour of day supported: " + isHourSupported);

This will check if HOUR_OF_DAY is supported by the LocalDate object and print the result.

Compile and run the program

In this step, you will compile and run the LocalDateDemo.java file. Open your terminal and execute the following commands:

javac ~/project/LocalDateDemo.java
java LocalDateDemo

Output

The output of the program should be:

Date: 2022-05-20
Is Month of year supported: true
Is Hour of day supported: false

Summary

In this lab, you learned how to use the isSupported() method in Java LocalDate. You learned how to create a LocalDate object, check if a field is supported, and check for an unsupported field using the isSupported() method.

Other Java Tutorials you may like