Java Duration

The Java Duration class is an immutable and thread-safe class that represents a quantity or amount of time in terms of seconds and nanoseconds.

How to use

The Java Duration class can be used to store and represent the time-based amount of time such as ‘30.45 seconds’. Try the following examples to better understand –

Add/Subtract time example

The following example program shows how you can plus/minus duration.

import java.time.Duration;

public class DurationExample1 {

    public static void main(String[] args) {

        // Duration with ZERO
        Duration duration = Duration.ZERO;

        // Add 10 minutes and print in seconds
        duration = duration.plusMinutes(10);
        System.out.println(duration.toSeconds());

        // Subtract 5 minutes and print in seconds
        duration = duration.minusMinutes(5);
        System.out.println(duration.toSeconds());
    }
}

Between example

The following example program shows how you can use between with Duration.

import java.time.Duration;
import java.time.LocalTime;

public class DurationExample2 {

    public static void main(String[] args) {

        // Duration using between
        Duration duration = Duration.between(LocalTime.MIN, LocalTime.MAX);

        // Print in hours
        System.out.println(duration.toHours());
    }
}

Negative check example

The following example program shows how you can check duration is in negative or not.

import java.time.Duration;
import java.time.LocalTime;

public class DurationExample3 {

    public static void main(String[] args) {

        // MAX to NOON is TRUE
        Duration duration = Duration.between(LocalTime.MAX, LocalTime.NOON);
        System.out.println(duration.isNegative());

        // NOON to MAX is false
        duration = Duration.between(LocalTime.NOON, LocalTime.MAX);
        System.out.println(duration.isNegative());
    }
}