- Java Date Time Tutorial
- Java System.currentTimeMillis()
- Java Time Measurement
- Java's java.util.Date
- Java's java.sql.Date
- Java's java.sql.Timestamp
- Java's java.util.Calendar and GregorianCalendar
- Java's java.util.TimeZone
- Parsing and Formatting Dates in Java
- Java Instant
- Java Duration
- Java LocalDate
- Java LocalTime
- Java LocalDateTime
- Java ZonedDateTime
- Java DateTimeFormatter
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 = Instant.now();
There are also other ways to create an
Instant. Check out the JavaDoc for more information.
Accessing the Time of an Instant
Instant object contains two fields internally which holds the time represented by the
- Seconds since the epoch.
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:
Instant class also has several methods which can be used to make calculations relative to an
Instant. Some (not all) of these methods are:
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.