Instants and durations

Description

Instants and durations allows us to record timestamps and elapsed time.

We can add and subtract a duration from an instant to get another instant.

By adding two durations we can get another duration.

Instant and Duration classes store second and nanosecond separately.

Example

The following code shows how how to get second and nanosecond from an Instant:


import java.time.Instant;
//from w  ww  .j a v a 2s  .c  om
public class Main {
  public static void main(String[] args) {
    Instant i1 = Instant.now();
   
    long seconds = i1.getEpochSecond();
    System.out.println(seconds);
    int nanoSeconds = i1.getNano();
    System.out.println(nanoSeconds);
  }
}

The code above generates the following result.

Example 2

The following code shows how to do Instant and Duration calculation.


import java.time.Duration;
import java.time.Instant;
//w  ww . java  2s.  c om
public class Main {
  public static void main(String[] args) {
    Duration d1 = Duration.ofSeconds(55);
    Duration d2 = Duration.ofSeconds(-17);
    
    Instant i1 = Instant.now();
    
    Instant i4 = i1.plus(d1);
    Instant i5 = i1.minus(d2);

    Duration d3 = d1.plus(d2);
    System.out.println(d3);
  }
}

The code above generates the following result.

Note

Instant and Duration are more often to work with machine-scale time.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial