Java Program to get duration between two time instants

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 25-Apr-2019 16:15:10
Advertisements