Sub topic 7
Instant: A Point on the Timeline
Earlier chapters covered LocalDate, LocalTime, and LocalDateTime. These types describe what a calendar or a wall clock shows. They do not say where in the world that calendar or clock is. So "2024-07-01 09:00" happens at different moments in New York and in Tokyo.
Sometimes you need one exact moment that is the same for everyone on Earth. Examples are the time an order was placed, the time a log line was written, or the time a payment cleared. For this, java.time gives you Instant.
What an Instant Is
An Instant is a single point on the timeline. It counts how much time has passed since a fixed starting point. It has no time zone, no calendar, and no "local" meaning. It is just a position on one long line of time.
That fixed starting point is called the epoch. The epoch is midnight at the start of January 1, 1970, in UTC. UTC (Coordinated Universal Time) is the world's reference time. It has no daylight saving changes. Java writes the epoch as 1970-01-01T00:00:00Z. The letter Z means "UTC". People sometimes call it "Zulu time".
Inside, an Instant stores two numbers:
- epoch seconds, a
longholding the whole seconds since the epoch. It can be negative for moments before 1970. - nanoseconds, an
intfrom 0 to 999,999,999 holding the fraction of the current second.
A nanosecond is one billionth of a second. So an Instant can be very precise, even if your computer's clock is not.
Creating Instants
You can create an Instant in several ways. All of them are static factory methods. A factory method is a static method that builds and returns a new object for you, so you never call new Instant(...) yourself.
import java.time.Instant;
public class CreatingInstants {
public static void main(String[] args) {
Instant epoch = Instant.EPOCH;
System.out.println(epoch); // 1970-01-01T00:00:00Z
Instant fromSeconds = Instant.ofEpochSecond(1_700_000_000L);
System.out.println(fromSeconds); // 2023-11-14T22:13:20Z
Instant fromMillis = Instant.ofEpochMilli(1_700_000_000_123L);
System.out.println(fromMillis); // 2023-11-14T22:13:20.123Z
Instant before1970 = Instant.ofEpochSecond(-86_400L);
System.out.println(before1970); // 1969-12-31T00:00:00Z
Instant parsed = Instant.parse("2024-07-01T13:00:00Z");
System.out.println(parsed); // 2024-07-01T13:00:00Z
Instant now = Instant.now();
System.out.println(now); // the current moment, for example 2026-11-23T13:17:06.045123Z
}
}Here is what each method does:
| Method | What it does |
|---|---|
| `Instant.EPOCH` | A constant for the epoch itself |
| `Instant.ofEpochSecond(long)` | Builds an instant from whole seconds since the epoch |
| `Instant.ofEpochMilli(long)` | Builds an instant from milliseconds since the epoch |
| `Instant.parse(String)` | Reads text such as `2024-07-01T13:00:00Z` |
| `Instant.now()` | Reads the current moment from the system clock |
Many other systems count time in milliseconds since the epoch. Unix timestamps, JavaScript's Date.now(), and System.currentTimeMillis() all work this way. ofEpochMilli is the bridge to those numbers.
Reading the Parts of an Instant
You can get the two stored numbers back. You can also get the total in milliseconds.
import java.time.Instant;
public class ReadingInstants {
public static void main(String[] args) {
Instant moment = Instant.parse("2024-07-01T13:00:00.250Z");
System.out.println(moment.getEpochSecond()); // 1719838800
System.out.println(moment.getNano()); // 250000000
System.out.println(moment.toEpochMilli()); // 1719838800250
}
}toEpochMilli() is the method you need when another library or a database column wants a plain long of milliseconds.
Doing Arithmetic with an Instant
Instant is immutable, like every other java.time type. Immutable means the object never changes after it is created. Methods such as plusSeconds return a new Instant, so you must store the result.
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class InstantMath {
public static void main(String[] args) {
Instant start = Instant.parse("2024-07-01T13:00:00Z");
System.out.println(start.plusSeconds(90)); // 2024-07-01T13:01:30Z
System.out.println(start.plusMillis(500)); // 2024-07-01T13:00:00.500Z
System.out.println(start.minus(1, ChronoUnit.HOURS)); // 2024-07-01T12:00:00Z
System.out.println(start.plus(1, ChronoUnit.DAYS)); // 2024-07-02T13:00:00Z
System.out.println(start.plus(Duration.ofMinutes(45))); // 2024-07-01T13:45:00Z
}
}ChronoUnit lists units such as hours and days. Duration is an amount of time such as "45 minutes". Later chapters cover both in detail. For now, you only need to know that you can add them to an Instant.
Why You Cannot Add a Month
Try adding one month to an Instant:
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class NoMonths {
public static void main(String[] args) {
Instant start = Instant.parse("2024-07-01T13:00:00Z");
try {
start.plus(1, ChronoUnit.MONTHS);
} catch (java.time.temporal.UnsupportedTemporalTypeException e) {
System.out.println(e.getMessage()); // Unsupported unit: Months
}
}
}This fails on purpose. An Instant does not know about calendars. A month can be 28, 29, 30, or 31 days long, and an Instant cannot tell which one you mean. A day is different: for an Instant, DAYS always means exactly 86,400 seconds. Units larger than days, such as weeks, months, and years, throw this exception.
To add months, first turn the instant into a ZonedDateTime in a time zone, then add the months. The next chapters show how.
Comparing Instants
Because every instant sits on the same timeline, comparing two of them is simple. No time zone can confuse the result.
import java.time.Instant;
public class CompareInstants {
public static void main(String[] args) {
Instant a = Instant.parse("2024-07-01T13:00:00Z");
Instant b = Instant.parse("2024-07-01T14:30:00Z");
System.out.println(a.isBefore(b)); // true
System.out.println(a.isAfter(b)); // false
System.out.println(a.equals(b)); // false
System.out.println(a.compareTo(b) < 0); // true
}
}Instant implements Comparable, so you can sort a List<Instant> with Collections.sort or list.sort(null).
Measuring Elapsed Time
A common use is timing how long something took. Capture an instant before and after, then measure the gap with Duration.between.
import java.time.Duration;
import java.time.Instant;
public class Elapsed {
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
Thread.sleep(200);
Instant end = Instant.now();
long millis = Duration.between(start, end).toMillis();
System.out.println("Took about " + millis + " ms"); // for example: Took about 201 ms
}
}Instant Compared with LocalDateTime
Beginners often mix these two types up. This table shows how they differ.
| Question | `Instant` | `LocalDateTime` |
|---|---|---|
| Does it name one exact moment worldwide? | Yes | No |
| Does it have a time zone? | No, it is always UTC | No, and it is not UTC either |
| Can it show year, month, and day directly? | No | Yes |
| Can you add months to it? | No | Yes |
| Typical use | Timestamps, logs, events | Wall-clock values like "meeting at 9:00" |
Use Instant when a machine records when something happened. Use the local types when a person thinks in terms of calendar dates and clock times.
Summary
- An
Instantis one exact moment, counted from the epoch1970-01-01T00:00:00Z. - It stores epoch seconds and nanoseconds, and it always prints in UTC.
- Create one with
now(),ofEpochSecond,ofEpochMilli, orparse. - You can add seconds, minutes, hours, days, and
Durationvalues. You cannot add months or years. - Comparing instants is safe because they all share one timeline.
Exercise
What does this code print? System.out.println(Instant.ofEpochSecond(60).plusMillis(1500));
Show answer
It prints 1970-01-01T00:01:01.500Z. Sixty seconds after the epoch is 00:01:00, and adding 1,500 milliseconds moves it 1.5 seconds later.
Exercise
A coworker writes Instant.now().plus(1, ChronoUnit.YEARS) to set an expiry date one year ahead. What happens, and why?
Show answer
It throws UnsupportedTemporalTypeException. An Instant has no calendar, so it cannot tell how long "one year" is (365 or 366 days). Convert the instant to a ZonedDateTime in a chosen zone first, add the year there, then convert back with toInstant().
Exercise
Write a line of code that turns the millisecond timestamp 1719838800000L into an Instant and prints it. What is the output?
Show answer
System.out.println(Instant.ofEpochMilli(1719838800000L)); prints 2024-07-01T13:00:00Z.