Java Data Type How to - Get duration between two time instants








Question

We would like to know how to get duration between two time instants.

Answer

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
/*from w ww. jav  a  2 s  .c om*/
public class Main {

  public static void main(String[] args) {
    Instant t1 = Instant.now();
    Instant t2 = Instant.now().plusSeconds(12);
    long nanos = Duration.between(t1, t2).toNanos();
    System.out.println(nanos);

    Duration gap = Duration.ofSeconds(13); // 12000000000
    Instant later = t1.plus(gap);
    System.out.println(t1); // 2014-07-02T19:55:00.956Z
    System.out.println(later); // 2014-07-02T19:55:13.956Z

    System.out.println(ChronoUnit.MILLIS.between(t1, t2)); // 12000
  }
}

The code above generates the following result.