Java 8 - Instant Class API Guide

  • One of the core classes of the Date-Time API is the Instant class, which represents the start of a nanosecond on the timeline. This class is used for generating a time stamp to represent machine time.
  • Java Instant class is used to represent the specific moment on the timeline.
Examples of this guide are available on Github.

Instant class provides lots of APIs/Methods but in this guide, we will discuss few important and frequently used Instant APIs/Methods with Examples.

Below class diagram shows a list APIs Instant class provides.


2. Instant Class Examples

2.1 Java Instant Example: parse()

import java.time.Instant;  
public class InstantExample1 {  
  public static void main(String[] args) {  
    Instant inst = Instant.parse("2017-02-03T10:37:30.00Z");  
    System.out.println(inst);  
  }  
}
Output:
2017-02-03T10:37:30Z

2.2 Java Instant Example: now()

import java.time.Instant;  
public class InstantExample2 {  
  public static void main(String[] args) {  
    Instant instant = Instant.now();  
    System.out.println(instant);    
  }  
}
Output:
2017-02-03T06:11:01.194Z

2.3 Java Instant Example: minus()

import java.time.*;  
public class InstantExample3 {  
  public static void main(String[] args) {  
    Instant instant = Instant.parse("2017-02-03T11:25:30.00Z");  
    instant = instant.minus(Duration.ofDays(125));  
    System.out.println(instant);   
  }  
}  
Output:
2016-10-01T11:25:30Z

2.4 Java Instant Example: plus()

import java.time.*;  
public class InstantExample4 {  
  public static void main(String[] args) {  
    Instant inst1 = Instant.parse("2017-02-03T11:25:30.00Z");  
    Instant inst2 = inst1.plus(Duration.ofDays(125));  
    System.out.println(inst2);   
  }  
}  
Output:
2017-06-08T11:25:30Z

2.5 Java Instant Example: isSupported()

import java.time.Instant;  
import java.time.temporal.ChronoUnit;  
public class InstantExample5 {  
  public static void main(String[] args) {  
    Instant inst = Instant.parse("2017-02-03T11:35:30.00Z");  
    System.out.println(inst.isSupported(ChronoUnit.DAYS));  
    System.out.println(inst.isSupported(ChronoUnit.YEARS));      
  }  
}  
Output:
true
false

Comments