Java Instant Examples

1. Introduction

In this tutorial, we explore the Instant class in Java, which represents a moment on the timeline in UTC.

The Instant class in Java is part of the java.time package, introduced in Java 8 as a part of the new date and time API which provides a more robust and flexible system for working with dates and times. 

Key Points

The Instant class represents a specific moment on the time-line, defined as the number of seconds and nanoseconds since the standard Java epoch of 1970-01-01T00:00:00Z. This makes it suitable for timestamping events in applications. 

Instant can store points on the time-line to nanosecond precision, providing a high degree of accuracy. It supports a wide range of dates, from approximately -1000000000-01-01T00:00Z to +1000000000-12-31T23:59:59.999999999Z, making it highly versatile for historical and futuristic time-stamping.

Like other classes in the java.time package, Instant is immutable. This immutability makes it thread-safe and helps in building reliable concurrent applications without the need for additional synchronization.

Instant can be easily converted to other date-time classes such as LocalDateTime, ZonedDateTime, and OffsetDateTime using methods like atZone(). This allows for flexible manipulation of date-time values, considering different time zones and localized contexts. 

The Instant class provides various utility methods for date-time arithmetic, such as plusSeconds, minusMillis, and until. It also offers methods for comparing instants, like isAfter, isBefore, and compareTo, making it easy to handle calculations and comparisons directly on the time-line.

2. Program Steps

1. Create an Instant representing the current moment and from a string.

2. Add and subtract time to/from an Instant.

3. Compare Instant objects to check if one is before or after another.

4. Calculate the difference in seconds between two Instant objects.

5. Convert an Instant to LocalDateTime, ZonedDateTime, and OffsetDateTime and back.

3. Code Program

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class Main {

    public static void main(String[] args) {

        // get an Instant
        Instant timestamp = Instant.now();
        System.out.println("Timestamp: " + timestamp);

        // String to Instant
        Instant timestampFromString = Instant.parse("2019-02-24T14:31:33.197021300Z");
        System.out.println("\\nTimestamp from string: " + timestampFromString);

        // Plus two hours
        Instant twoHourLater = Instant.now().plus(2, ChronoUnit.HOURS);
        System.out.println("\\nTwo hours later: " + twoHourLater);

        // Minus 10 minutes
        Instant tenMinutesEarlier = Instant.now().minus(10, ChronoUnit.MINUTES);
        System.out.println("Ten minutes earlier: " + tenMinutesEarlier);

        // check if one Instant is after another Instant
        Instant timestamp1 = Instant.now();
        Instant timestamp2 = timestamp1.plusSeconds(10);
        boolean isAfter = timestamp1.isAfter(timestamp2);
        System.out.println("\\n" + timestamp1 + " is " + (isAfter ? "" : "not ") + "after " + timestamp2);

        // check if one Instant is before another Instant
        boolean isBefore = timestamp1.isBefore(timestamp2);
        System.out.println(timestamp1 + " is " + (isBefore ? "" : "not ") + "before " + timestamp2);

        // difference between two Instants
        long difference = timestamp1.until(timestamp2, ChronoUnit.SECONDS);
        System.out.println("Between " + timestamp1 + " and " + timestamp2 + " there are " + difference + " seconds");

        // convert Instant to LocalDateTime
        LocalDateTime ldt = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC);
        System.out.println("\\nInstant to LocaleDateTime: " + ldt);
        // convert LocalDateTime to Instant
        Instant instantLDT = LocalDateTime.now().toInstant(ZoneOffset.UTC);
        System.out.println("LocaleDateTime to Instant: " + instantLDT);

        // convert Instant to ZonedDateTime
        ZonedDateTime zdt = Instant.now().atZone(ZoneId.of("Europe/Paris"));
        System.out.println("Instant to ZonedDateTime: " + zdt + " (offset: " + zdt.getOffset() + ")");
        // convert ZonedDateTime to Instant
        Instant instantZDT = LocalDateTime.now().atZone(ZoneId.of("Europe/Paris")).toInstant();
        System.out.println("ZonedDateTime to Instant: " + instantZDT);

        // convert Instant to OffsetDateTime
        OffsetDateTime odt = Instant.now().atOffset(ZoneOffset.of("+02:00"));
        System.out.println("Instant to OffsetDateTime: " + odt + " (offset: " + odt.getOffset() + ")");
        // convert OffsetDateTime to Instant
        Instant instantODT = LocalDateTime.now().atOffset(ZoneOffset.of("+02:00")).toInstant();
        System.out.println("OffsetDateTime to Instant: " + instantODT);
    }
}

Output:

Timestamp: 2021-11-10T12:49:11.236292200Z
Timestamp from string: 2019-02-24T14:31:33.197021300Z
Two hours later: 2021-11-10T14:49:11.304788800Z
Ten minutes earlier: 2021-11-10T12:39:11.304788800Z
2021-11-10T12:49:11.304788800Z is not after 2021-11-10T12:49:21.304788800Z
2021-11-10T12:49:11.304788800Z is before 2021-11-10T12:49:21.304788800Z
Between 2021-11-10T12:49:11.304788800Z and 2021-11-10T12:49:21.304788800Z there are 10 seconds
Instant to LocaleDateTime: 2021-11-10T12:49:11.305785800
LocaleDateTime to Instant: 2021-11-10T18:19:11.338699600Z
Instant to ZonedDateTime: 2021-11-10T13:49:11.338699600+01:00[Europe/Paris] (offset: +01:00)
ZonedDateTime to Instant: 2021-11-10T17:19:11.347674900Z
Instant to OffsetDateTime: 2021-11-10T14:49:11.356655100+02:00 (offset: +02:00)
OffsetDateTime to Instant: 2021-11-10T16:19:11.357650400Z

Explanation:

1. Instant.now() creates an Instant representing the current moment.

2. Instant.parse("2019-02-24T14:31:33.197021300Z") creates an Instant from a formatted string.

3. Instant.now().plus(2, ChronoUnit.HOURS) calculates two hours later from the current instant.

4. Instant.now().minus(10, ChronoUnit.MINUTES) calculates ten minutes earlier from the current instant.

5. timestamp1.isAfter(timestamp2) checks if timestamp1 is after timestamp2.

6. timestamp1.isBefore(timestamp2) checks if timestamp1 is before timestamp2.

7. timestamp1.until(timestamp2, ChronoUnit.SECONDS) calculates the difference in seconds between two instants.

8. LocalDateTime.ofInstant(Instant.now(), ZoneOffset.UTC) converts an Instant to LocalDateTime.

9. LocalDateTime.now().toInstant(ZoneOffset.UTC) converts LocalDateTime to an Instant.

10. Instant.now().atZone(ZoneId.of("Europe/Paris")) converts an Instant to ZonedDateTime.

11. LocalDateTime.now().atZone(ZoneId.of("Europe/Paris")).toInstant() converts ZonedDateTime to an Instant.

12. Instant.now().atOffset(ZoneOffset.of("+02:00")) converts an Instant to OffsetDateTime.

13. LocalDateTime.now().atOffset(ZoneOffset.of("+02:00")).toInstant() converts OffsetDateTime to an Instant.

Comments