Java Instant

The Java Instant class is an immutable and thread-safe class that represents a single instantaneous point on the timeline.

How to use

The Instant class requires storage of a number larger than a long. To achieve this it uses a long for epoch-seconds and an int for nanosecond-of-second, which will always be between 0 and 999,999,999. Try the following examples to better understand –

Now example

The following example program shows how you can create an instance of Instant and get the current date and time.

import java.time.Instant;

public class InstantExample1 {

    public static void main(String[] args) {

        // Create instance of instant
        Instant instant = Instant.now();

        // Print current date and time
        System.out.println(instant);
    }
}

Add/Subtract example

The following example program shows how you can plus/minus time in Instant.

import java.time.Instant;

public class InstantExample2 {

    public static void main(String[] args) {

        // Create instance of instant
        Instant instant = Instant.now();
        System.out.println(instant);

        // Add 5 minutes
        instant = instant.plusSeconds(60 * 5);
        System.out.println(instant);

        // Subtract 5 minutes
        instant = instant.plusSeconds(60 * 5);
        System.out.println(instant);
    }
}

Parse example

The following example program shows how you can parse and create Instant from string.

import java.time.Instant;
import java.time.temporal.ChronoField;

public class InstantExample3 {

    public static void main(String[] args) {

        // Parse and create instant from string
        Instant instant = Instant.parse("2019-05-07T06:00:55.450Z");

        // Print the milli second
        System.out.println(instant.get(ChronoField.MILLI_OF_SECOND));
    }
}