Skip to content
On this page

Instant and Time Conversion

As we've discussed, the current time stored by computers is essentially just a continuously increasing integer. In Java, the method System.currentTimeMillis() returns the current timestamp in milliseconds.

In the java.time package, the current timestamp is represented by the Instant type, which you can get using Instant.now(). This works similarly to System.currentTimeMillis():

java
import java.time.*;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now.getEpochSecond()); // Seconds
        System.out.println(now.toEpochMilli()); // Milliseconds
    }
}

The output will look something like this:

1568568760
1568568760316

Internally, Instant contains only two core fields:

java
public final class Instant implements ... {
    private final long seconds;
    private final int nanos;
}

One field represents the timestamp in seconds, while the other provides higher precision with nanoseconds. This is just a more precise representation compared to the long returned by System.currentTimeMillis().

Since Instant represents a timestamp, you can create a ZonedDateTime by associating it with a timezone:

java
// Create Instant from a specified timestamp:
Instant ins = Instant.ofEpochSecond(1568568760);
ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
System.out.println(zdt); // 2019-09-16T01:32:40+08:00[Asia/Shanghai]

As shown, by associating a specific timestamp with a ZoneId, you obtain a ZonedDateTime, which allows you to derive the corresponding LocalDateTime.

The following conversions are possible:

┌─────────────┐
│LocalDateTime│────┐
└─────────────┘    │    ┌─────────────┐
                   ├───▶│ZonedDateTime│
┌─────────────┐    │    └─────────────┘
│   ZoneId    │────┘           ▲
└─────────────┘      ┌─────────┴─────────┐
                     │                   │
                     ▼                   ▼
              ┌─────────────┐     ┌─────────────┐
              │   Instant   │◀───▶│    long     │
              └─────────────┘     └─────────────┘

When converting, just keep in mind whether the long type is in milliseconds or seconds.

Summary

Instant represents a high-precision timestamp and can be converted to and from ZonedDateTime and long.

Instant and Time Conversion has loaded