Java Calculate Number of Milliseconds Between two Instant

Tags: Java Instant ChronoUnit Java 8

In this Java core tutorial, we learn how to calculate the number of milliseconds between two Instant objects using the java.time.temporal.ChronoUnit class in Java programming language.

How to get number of milliseconds between Instant in Java

In Java, we can use the ChronoUnit.MILLIS.between() method to calculate the number of milliseconds between two Instant values as the following example Java program.

MillisecondsBetweenInstantExample.java

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class MillisecondsBetweenInstantExample {
    public static void main(String... args) {
        Instant startInstant = Instant.parse("2022-08-13T12:00:00.0Z");
        Instant endInstant = Instant.parse("2022-08-13T12:02:30.0Z");

        // Calculate Number of Milliseconds Between two Instant
        long numberOfMilliseconds = ChronoUnit.MILLIS.between(startInstant, endInstant);

        System.out.println(String.format("Number of milliseconds between %s and %s is %d", startInstant, endInstant, numberOfMilliseconds));
    }
}
The output as below.
Number of milliseconds between 2022-08-13T12:00:00Z and 2022-08-13T12:02:30Z is 150000

Happy Coding 😊

Java Calculate Number of Days Between two Instant

Java Calculate Number of Hours Between two Instant

Java Calculate Number of Minutes Between two Instant

Java Calculate Number of Seconds Between two Instant

Java Calculate Number of Nanoseconds Between two Instant