Instant isSupported() method in Java


It can be checked if a ChronoUnit is supported by the Instant class or not by using the isSupported() method in the Instant 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 Instant class and false otherwise.

A program that demonstrates this is given as follows −

Example

 Live Demo

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

Output

The current instant is: 2019-02-13T07:08:32.900Z
The ChronoUnit SECONDS 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 SECONDS is supported by the Instant 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 −

Instant i = Instant.now();
System.out.println("The current instant is: " + i);
boolean flag = i.isSupported(ChronoUnit.SECONDS);
if(flag)
   System.out.println("The ChronoUnit SECONDS is supported");
else
   System.out.println("The ChronoUnit SECONDS is not supported");

Updated on: 30-Jul-2019

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements