Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Instant

An exact moment on the UTC timeline — for logs, timestamps and measurements.

Available since: Java 8

Syntax

public final class Instant implements Temporal, Comparable<Instant>

Examples

The current moment — the output changes on every run:

void main() {
    Instant now = Instant.now();
    IO.println(now);
    IO.println(now.getEpochSecond() > 0);
}

Output:

2026-10-04T06:22:33.382291100Z
true

A moment from Unix time, and the difference between moments:

void main() {
    Instant start = Instant.ofEpochSecond(1_700_000_000);
    Instant end = start.plus(Duration.ofMinutes(90));
    IO.println(start);
    IO.println(Duration.between(start, end).toMinutes());
    IO.println(start.atZone(ZoneId.of("Europe/Berlin")).toLocalTime());
}

Output:

2023-11-14T22:13:20Z
90
23:13:20

Notes

An Instant is always in UTC (the Z in the output) and does not depend on the computer's time zone. To show it to a person, convert it to a zone: instant.atZone(zone). Unix time in milliseconds is Instant.ofEpochMilli() and toEpochMilli().

See also

  • ZonedDateTime — A date and time in a specific time zone — with daylight saving time taken into account.
  • Duration — An amount of time in seconds and nanoseconds — hours, minutes, seconds.
  • LocalDateTime — A date and time without a time zone — for example, a meeting in a calendar.

Related recipes

In the tutorial

  • Dates and times — The java.time package — LocalDate, LocalTime, LocalDateTime, date arithmetic, Period, Duration, ChronoUnit, time zones and Instant.

Thanks for reading!

Donate to the site — we work hard for you.