Get Duration Between Two Time Instants in Java



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: 2019-07-30T22:30:25+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements