Java Program to get Milliseconds between two time instants

Java 8Object Oriented ProgrammingProgramming

At first, create two time instants −

Instant time1 = Instant.now();
Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);

Use between() to get the milliseconds between two time instants −

Duration duration = Duration.ofSeconds(13);
Instant i = time1.plus(duration);
System.out.println("Milliseconds between two time instants = "+ChronoUnit.MILLIS.between(time1, time2));

Example

 Live Demo

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant time1 = Instant.now();
      Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);
      Duration duration = Duration.ofSeconds(13);
      Instant i = time1.plus(duration);
      System.out.println("Milliseconds between two time instants =
         "+ChronoUnit.MILLIS.between(time1, time2));
   }
}

Output

Milliseconds between two time instants = 18050000
raja
Published on 24-Apr-2019 12:10:02
Advertisements