Instants

Description

An instant represents a unique moment in time.

An epoch is an instant used as origin to measure other instants. The epoch is at 1970-01-01T00:00:00Z.

The time between two consecutive instants is one nanosecond.

Instants after the epoch have positive values while instants before the epoch have negative values.

The instant at the epoch is assigned a zero value.

Example

We can use Instant.now() to get the current instant using the system default clock.


import java.time.Instant;
//from  w  ww .ja  v a 2s. com
public class Main {
  public static void main(String[] args) {
    Instant instantNow = Instant.now();
    System.out.println(instantNow);
  }
}

The code above generates the following result.

Example 2

You can create an Instant from epoch offset.

The following code creates an Instant object to represent 9 seconds from the epoch.


import java.time.Instant;
/* w w  w. j  av a 2  s  .  c o  m*/
public class Main {
  public static void main(String[] args) {
    Instant instance9 = Instant.ofEpochSecond(9);
    System.out.println(instance9);
    
    instance9 = Instant.ofEpochSecond(-9);
    System.out.println(instance9);
  }
}

The code above generates the following result.

Note

Two instants can be compared to know whether one occurs before or after other.

Instants and durations are used for recording timestamps and elapsed time between two events.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial