Java Create Duration Between Instant

Tags: Java Instant Java 8

In this Java core tutorial we learn how to create a new Duration object from given start and end Instant values using date time API in Java programming language.

How to create Duration between Instant in Java

In Java, with given start Instant object and end Instant object we can use the Duration.between(Temporal startInclusive, Temporal endExclusive) method to create a new Duration object as the following example Java code.

DurationBetweenInstantExample1.java

import java.time.Duration;
import java.time.Instant;

public class DurationBetweenInstantExample1 {
    public static void main(String... args) {
        Instant start = Instant.parse("2022-06-14T08:30:30.111111111Z");
        Instant end = Instant.parse("2022-06-14T12:00:00.111111111Z");

        Duration duration = Duration.between(start, end);

        System.out.println("Start Instant: " + start);
        System.out.println("End Instant: " + end);
        System.out.println("Duration: " + duration);
    }
}
The output as below.
Start Instant: 2022-06-14T08:30:30.111111111Z
End Instant: 2022-06-14T12:00:00.111111111Z
Duration: PT3H29M30S

Happy Coding 😊

Java Create Duration Between LocalDateTime