LocalDateTime isSupported() method in Java

Java 8Object Oriented ProgrammingProgramming

It can be checked if a ChronoUnit is supported by the LocalDateTime class or not by using the isSupported() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the ChronoUnit to check. It returns true if the ChronoUnit is supported by the LocalDateTime class and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
import java.time.temporal.*;
public class Demo {
   public static void main(String[] args) {
      LocalDateTime ldt = LocalDateTime.now();
      System.out.println("The LocalDateTime is: " + ldt);
      boolean flag = ldt.isSupported(ChronoUnit.HOURS);
      if(flag)
         System.out.println("The ChronoUnit HOURS is supported");
      else
         System.out.println("The ChronoUnit HOURS is not supported");
   }
}

Output

The LocalDateTime is: 2019-02-18T07:12:12.472
The ChronoUnit HOURS is supported

Now let us understand the above program.

First the current instant is displayed. Then the isSupported() method is used to check if the ChronoUnit HOURS is supported by the LocalDateTime class or not. The returned value is stored in flag and the appropriate response is printed. A code snippet that demonstrates this is as follows −

LocalDateTime ldt = LocalDateTime.now();
System.out.println("The LocalDateTime is: " + ldt);
boolean flag = ldt.isSupported(ChronoUnit.HOURS);
if(flag)
   System.out.println("The ChronoUnit HOURS is supported");
else
   System.out.println("The ChronoUnit HOURS is not supported");
raja
Updated on 30-Jul-2019 22:30:25

Advertisements