Java Program to get duration between two time instants


Create two time instants:

Instant time1 = Instant.now();
Instant time2 = Instant.now().plusSeconds(50);

Use between() to get the duration between two time instants:

long resMilli = Duration.between(time1, time2).toMillis();

Example

import java.time.Duration;
import java.time.Instant;
public class Demo {
   public static void main(String[] args) {
      Instant time1 = Instant.now();
      Instant time2 = Instant.now().plusSeconds(50);
      long resMilli = Duration.between(time1, time2).toMillis();
      System.out.println("Duration between two time intervals = "+resMilli);
   }
}

Output

Duration between two time intervals = 50000

Updated on: 30-Jul-2019

190 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements