Tech and Media Labs
This site uses cookies to improve the user experience.




Java Instant

Jakob Jenkov
Last update: 2015-06-22

The Instant class in the Java date time API (java.time.Instant) represents a specific moment on the time line. The instant is defined as an offset since the origin (called an epoch). The origin is Jan. 1st 1970 - 00:00 - Greenwhich mean time (GMT).

Time is measured using 86.400 seconds per day, moving forward from the origin.

Creating an Instant

You create an Instant instance using one of the Instant class factory methods. For instance, to create an Instant which represents this exact moment of now, call Instant.now(), like this:

Instant now = Instant.now();

There are also other ways to create an Instant. Check out the JavaDoc for more information.

Accessing the Time of an Instant

An Instant object contains two fields internally which holds the time represented by the Instant:

  • Seconds since the epoch.
  • Nanoseconds

The seconds since the epoch is the number of seconds since the origin mentioned in the beginning of this tutorial. The nanoseconds is the part of that Instant which is less than one second.

You can access both the seconds and nanoseconds via these methods:

  • getEpochSecond()
  • getNano()

Instant Calculations

The Instant class also has several methods which can be used to make calculations relative to an Instant. Some (not all) of these methods are:

  • plusSeconds()
  • plusMillis()
  • plusNanos()
  • minusSeconds()
  • minusMillis()
  • minusNanos()

I will show you two examples below to illustrate how these methods work:

Instant now     = Instant.now();

Instant later   = now.plusSeconds(3);
Instant earlier = now.minusSeconds(3);

The first line creates a new Instant representing the moment of now. The second line creates an Instant that represents the moment 3 seconds earlier, and the third line creates an Instant that represents the moment 3 seconds later.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC