Java Duration between()

In this guide, you will learn about the Duration between() method in Java programming and how to use it with an example.

1. Duration between() Method Overview

Definition:

The Duration.between() method is a static method in the java.time.Duration class is used to get the duration between two temporal points.

Syntax:

public static Duration between(Temporal startInclusive, Temporal endExclusive)

Parameters:

- startInclusive: The start temporal point, inclusive. Should be of type Temporal.

- endExclusive: The end temporal point, exclusive. Should be of type Temporal.

Key Points:

- The Duration.between() method returns a Duration instance that represents the time span between two temporal points.

- Both temporal points must support the SECOND and NANO units; otherwise, a DateTimeException is thrown.

- The result of the method will have a positive or negative sign depending on the order of the temporal points provided (i.e., if the end is before the start, a negative duration will be returned).

- The commonly used temporal types with this method are LocalDateTime, Instant, and OffsetDateTime.

2. Duration between() Method Example

import java.time.Duration;
import java.time.LocalDateTime;

public class DurationBetweenExample {
    public static void main(String[] args) {
        LocalDateTime startDateTime = LocalDateTime.of(2023, 1, 1, 10, 0);
        LocalDateTime endDateTime = LocalDateTime.of(2023, 1, 1, 12, 30);

        // Calculate the duration between the two LocalDateTime instances
        Duration duration = Duration.between(startDateTime, endDateTime);

        // Print the duration
        System.out.println("Duration: " + duration);
    }
}

Output:

Duration: PT2H30M

Explanation:

In the provided example, we have two LocalDateTime instances, representing 10:00 and 12:30 on January 1, 2023. 

We then use the Duration.between() method to calculate the time span between the two points. 

The resulting duration is 2 hours and 30 minutes, represented as PT2H30M. The "PT" prefix is a standard ISO-8601 representation, where "P" stands for a period and "T" separates the date and time components.

Comments