Instant get() method in Java

Java 8Object Oriented ProgrammingProgramming

The value of the required ChronoField for an Instant can be obtained using the get() method in the Instant class in Java. This method requires a single parameter i.e. the ChronoField and it returns the value of the ChronoField that was passed as a parameter.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ValueRange;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      int micro = i.get(ChronoField.MICRO_OF_SECOND);
      System.out.println("The current Instant is: " + i);
      System.out.println("The MICRO_OF_SECOND Field is: " + micro);
   }
}

Output

The current Instant is: 2019-02-13T11:07:48.456Z
The MICRO_OF_SECOND Field is: 456000

Now let us understand the above program.

First, the current instant is displayed. Then the value of the MICRO_OF_SECOND ChronoField is obtained using the get() method and displayed. A code snippet that demonstrates this is as follows −

Instant i = Instant.now();
int micro = i.get(ChronoField.MICRO_OF_SECOND);
System.out.println("The current Instant is: " + i);
System.out.println("The MICRO_OF_SECOND Field is: " + micro);
raja
Published on 26-Mar-2019 09:54:48
Advertisements