You are currently viewing Duration Class in Java

Duration Class in Java

1. Introduction

Java 8 introduced, through JSR 310, a complete overhaul of the Date/Time API by providing new, more advanced classes for Date processing. Duration is one such class that we will focus on in this article.

Affiliate Disclosure
This post contains affiliate links. If you purchase through these links, I may earn a small commission at no additional cost to you. As an Amazon Associate, I earn from qualifying purchases.

2. What is a Duration?

Duration is a class from the java.time package, which models a time-based amount of time, such as ‘2 hours’. The class represents a quantity or amount of time in terms of days, hours, minutes, seconds, or nanoseconds.
The Period class is date-based equivalent to this class.

The main particularity of Duration is that it is immutable and thread-safe.

3. Creating a Duration

3.1. Duration.ofXXX()

You can create a Duration object with any of the Duration.ofXXX() methods.

        Duration ofDays = Duration.ofDays(1);//PT24H
        Duration ofHours = Duration.ofHours(1);//PT1H
        Duration ofMinutes = Duration.ofMinutes(1);//PT1M
        Duration ofSeconds = Duration.ofSeconds(1);//PT1S
        Duration ofMillis = Duration.ofMillis(1);//PT0.001S
        Duration ofNanos = Duration.ofNanos(1);//PT0.000000001S

Additionally, you can use the generic Duration.of() method with a TemporalUnit parameter. The TemporalUnit object must have an exact duration (see Duration.isDurationEstimated()) or be ChronoUnit.DAYS.

        Duration ofDays = Duration.of(1,ChronoUnit.DAYS);//PT24H
        Duration ofHours = Duration.of(1,ChronoUnit.HOURS);//PT1H
        Duration ofMinutes = Duration.of(1,ChronoUnit.MINUTES);//PT1M
        Duration ofSeconds = Duration.of(1,ChronoUnit.SECONDS);//PT1S
        Duration ofMillis = Duration.of(1,ChronoUnit.MILLIS);//PT0.001S
        Duration ofNanos = Duration.of(1,ChronoUnit.NANOS);//PT0.000000001S

If the TemporalUnit you provide does not have an exact duration as described above, an UnsupportedTemporalTypeException is thrown:

        Duration incorrectDuration = Duration.of(1,ChronoUnit.MONTHS);//UnsupportedTemporalTypeException

3.2. Parsing from String to Duration

Assuming that you have a Duration in ISO-8601 format and want to build a Duration out of it, you can use the parse() method in this way:

        String myDuration = "PT24H";// ISO-8601 Duration format
        Duration duration = Duration.parse(myDuration);// PT24H

A Duration can be negative as well:

        String myDuration = "PT-24H";// ISO-8601 Duration format
        Duration duration = Duration.parse(myDuration);// PT-24H

The accepted ISO-8601 duration format is as follows: PnDTnHnMn.nS.
In the above format, “n” is an integer; D, H, M, and S are suffixes. Check out the detailed information about the duration ISO-8601 format here.

Any days input is treated as a duration of exactly 24 hours:

        String myDuration = "P2D";// ISO-8601 Duration format
        Duration duration = Duration.parse(myDuration);// PT48H (not P2D)

Java will throw a DateTimeParseException if it is not able to parse the String with the given time format.

    String myDuration = "PT24n";// Incorrect format
    Duration duration = Duration.parse(myDuration);// DateTimeParseException

3.3. Difference between two Temporal Objects

You can obtain a Duration as the difference between two Temporal objects:

        LocalTime firstTime = LocalTime.of(13,30);//13:30
        LocalTime secondTime = LocalTime.of(14,30);//14:30
        Duration duration = Duration.between(firstTime,secondTime);//PT1H

4. Operating on a Duration

4.1. Comparing two Duration objects

Since the Duration class implements the Comparable<E> interface, you may use the compareTo() method:

        Duration firstDuration = Duration.of(1,ChronoUnit.DAYS);
        Duration secondDuration = Duration.of(1,ChronoUnit.HOURS);
        Duration thirdDuration = Duration.of(2,ChronoUnit.DAYS);
        int test1 = firstDuration.compareTo(secondDuration);// A positive number
        int test2 = firstDuration.compareTo(thirdDuration);// A negative number

Furthermore, you should know that the Duration class also overrides the equals() method and provides a convenient way to check the equality of two Duration objects:

        Duration firstDuration = Duration.of(1,ChronoUnit.DAYS);
        Duration secondDuration = Duration.of(24,ChronoUnit.HOURS);
        Duration thirdDuration = Duration.of(1,ChronoUnit.DAYS);
        boolean test1 = firstDuration.equals(secondDuration);// true
        boolean test2 = firstDuration.equals(thirdDuration);// true

4.2. Temporal Arithmetic with Duration Objects

The Duration class provides plusXXX() and minusXXX() methods to increment and decrement the object field values. Since the Duration is immutable, all these methods return a copy of the original object with the given fields updated.

        Duration duration = Duration.of(1,ChronoUnit.DAYS);//PT24H
        Duration plusDays = duration.plusDays(1);//PT48H
        Duration minusDays = duration.minusDays(1);//PT0S
        Duration plusHours = duration.plusHours(1);//PT25H
        Duration minusHours = duration.minusHours(1);//PT23H
        Duration plusMinutes = duration.plusMinutes(1);//PT24H1M
        Duration minusMinutes = duration.minusMinutes(1);//PT23H59M
        Duration plusSeconds = duration.plusSeconds(1);//PT24H1S
        Duration minusSeconds = duration.minusSeconds(1);//PT23H59M59S

You can also use the plus() and minus() to add and subtract two Duration objects directly:

        Duration duration = Duration.of(1,ChronoUnit.DAYS);//PT24H
        Duration toAdd = Duration.of(1,ChronoUnit.HOURS);//PT1H
        Duration addedDuration = duration.plus(toAdd);//PT25H
        Duration subtractedDuration = duration.minus(toAdd);//PT23H

Lastly, the plus() and minus() methods have overloaded versions that accept a long and a TemporalUnit:

        Duration duration = Duration.of(1,ChronoUnit.DAYS);//PT24H
        Duration addedDuration = duration.plus(1, ChronoUnit.HOURS);//PT25H
        Duration substractedDuration = duration.minus(1, ChronoUnit.HOURS);//PT23H

5. Conclusion

In this tutorial, you learned about the Duration class in Java.

6. References

1) OCP Oracle Certified Professional Java SE 17 by Khalil A. Mughal and Vasily A. Strelnikov
2) Oracle Java Documentation

Noel Kamphoa

Experienced software engineer with expertise in Telecom, Payroll, and Banking. Now Senior Software Engineer at Societe Generale Paris.