java.time.Duration Tutorial with Examples

Duration class represents a time-based amount of time between two Instant objects, such as '25.5 seconds'. Duration class stores a long representing seconds and an int representing nanosecond-of-second, the value may be negative. This class is immutable and thread-safe.

Creating a Duration

We can create a Duration object by using one of the Duration class factory methods:

Another factory method that common in use for Duration is between() method:

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

public class DurationInitExample {

    public static void main(String[] args) {
        Duration duration1 = Duration.ofDays(7);
        System.out.println("Duration1: " + duration1);

        Duration duration2 = Duration.ofHours(8);
        System.out.println("Duration2: " + duration2);
        
        Duration duration3 = Duration.ofMinutes(15);
        System.out.println("Duration3: " + duration3);
        
        Duration duration4 = Duration.ofSeconds(10);
        System.out.println("Duration4: " + duration4);
        
        Duration duration5 = Duration.ofSeconds(30, 123456789);
        System.out.println("Duration5: " + duration5);
        
        Duration duration6 = Duration.parse("P1DT8H15M10.345000S");
        System.out.println("Duration6: " + duration6);        
        
        Duration duration7 = Duration.between(LocalDateTime.of(2019,1, 1, 0, 0), LocalDateTime.now());
        System.out.println("Duration7: " + duration7);
    }
}
                    

Duration1: PT168H
Duration2: PT8H
Duration3: PT15M
Duration4: PT10S
Duration5: PT30.123456789S
Duration6: PT32H15M10.345S
Duration7: PT5777H59M59.967S

Accessing Information from a Duration

Duration class models a quantity or amount of time in terms of seconds and nanoseconds. The two information can be accessed through these methods:

  • long getSeconds(): Gets the number of seconds in this duration.
  • int getNano(): Gets the number of nanoseconds within the second in this duration.

Use get(...) with requested unit to get the value of the unit in the duration:

Following function is to get all units supported:

  • List<TemporalUnit> getUnits(): Gets the set of units supported by this duration.
DurationGetExample.java
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;

public class DurationGetExample {
    
    public static void main(String[] args) {
        Duration duration = Duration.parse("P1DT8H15M10.345000S");
        System.out.println("Duration  : " + duration);
        System.out.println("Seconds   : " + duration.getSeconds());
        System.out.println("Nano      : " + duration.getNano());
        
        System.out.println("NANOS     : " + duration.get(ChronoUnit.NANOS));
        System.out.println("SECONDS   : " + duration.get(ChronoUnit.SECONDS));
        
        System.out.println("\n#getUnits():");
        List<TemporalUnit> units = duration.getUnits();
        for (TemporalUnit unit : units) {
            System.out.println("- " + unit);
        }        
    }
}
                    

Duration  : PT32H15M10.345S
Seconds   : 116110
Nano      : 345000000
NANOS     : 345000000
SECONDS   : 116110

#getUnits():
- Seconds
- Nanos

Duration also can be accessed using other duration-based units, such as minutes and hours. In addition, the DAYS unit can be used and is treated as exactly equal to 24 hours. You convert a Duration to these time units using these conversion methods:

  • long toDays(): Gets the number of days in this duration.
  • long toHours(): Gets the number of hours in this duration.
  • long toMillis(): Converts this duration to the total length in milliseconds.
  • long toMinutes(): Gets the number of minutes in this duration.
  • long toNanos(): Converts this duration to the total length in nanoseconds expressed as a long.

And these methods available since Java 9:

  • long toDaysPart(): Extracts the number of days in the duration.
  • int toHoursPart(): Extracts the number of hours part in the duration.
  • int toMillisPart(): Extracts the number of milliseconds part of the duration.
  • int toMinutesPart(): Extracts the number of minutes part in the duration.
  • int toNanosPart(): Get the nanoseconds part within seconds of the duration.
  • long toSeconds(): Gets the number of seconds in this duration.
  • int toSecondsPart(): Extracts the number of seconds part in the duration.
DurationToExample.java
import java.time.Duration;

public class DurationToExample {
    
    public static void main(String[] args) {
        Duration duration = Duration.parse("P3DT12H45M30.345000S");
        System.out.println("Duration   : " + duration);
        System.out.println("Days       : " + duration.toDays());
        System.out.println("Hours      : " + duration.toHours());
        System.out.println("Minutes    : " + duration.toMinutes());
        System.out.println("Millis     : " + duration.toMillis());
        System.out.println("Nanos      : " + duration.toNanos());        
        
        System.out.println("DaysPart   : " + duration.toDaysPart());
        System.out.println("HoursPart  : " + duration.toHoursPart());
        System.out.println("MillisPart : " + duration.toMillisPart());
        System.out.println("MinutesPart: " + duration.toMinutesPart());
        System.out.println("Seconds    : " + duration.toSeconds());
        System.out.println("SecondsPart: " + duration.toSecondsPart());
        System.out.println("NanosPart  : " + duration.toNanosPart());        
    }
}
                    

Duration   : PT84H45M30.345S
Days       : 3
Hours      : 84
Minutes    : 5085
Millis     : 305130345
Nanos      : 305130345000000
DaysPart   : 3
HoursPart  : 12
MillisPart : 345
MinutesPart: 45
Seconds    : 305130
SecondsPart: 30
NanosPart  : 345000000

isNegative() and isZero() to check if duration's length is negative or zero:

  • boolean isNegative(): Checks if this duration is negative, excluding zero.
  • boolean isZero(): Checks if this duration is zero length.
DurationInfoExample.java
import java.time.Duration;
import java.time.Instant;

public class DurationInfoExample {
    
    public static void main(String[] args) {
        Duration duration1 = Duration.parse("P1DT8H15M10.345000S");
        System.out.println("Duration1  : " + duration1);
        System.out.println("#isNegative: " + duration1.isNegative());
        System.out.println("#isZero    : " + duration1.isZero());
        
        Instant instant1 = Instant.now();
        Duration duration2 = Duration.between(instant1, instant1);
        System.out.println("\nDuration2  : " + duration2);
        System.out.println("#isNegative: " + duration2.isNegative());
        System.out.println("#isZero    : " + duration2.isZero());
        
        Instant instant2 = Instant.now();
        Duration duration3 = Duration.between(instant2, instant1);
        System.out.println("\nDuration3  : " + duration3);
        System.out.println("#isNegative: " + duration3.isNegative());
        System.out.println("#isZero    : " + duration3.isZero());
    }
}
                    

Duration1  : PT32H15M10.345S
#isNegative: false
#isZero    : false

Duration2  : PT0S
#isNegative: false
#isZero    : true

Duration3  : PT-0.002S
#isNegative: true
#isZero    : false

if start and end is same, then the duration's length is zero. If start is bigger than end, then is negative.

Plus/Minus Operations on Duration

The Duration class also has several methods which can be used to do add/subtract operations:

DurationPlusMinusExample.java
import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class DurationPlusMinusExample {

    public static void main(String[] args) {
        Duration duration = Duration.parse("P1DT8H15M10.345000S");
        System.out.println("Duration            : " + duration);
        
        // Adding/subtracting days
        System.out.println("10 days before      : " + duration.minusDays(10));
        System.out.println("15 days later       : " + duration.plusDays(15));
        
        // Adding/subtracting hours
        System.out.println("12 hours before     : " + duration.minusHours(12));
        System.out.println("6 hours later       : " + duration.plusHours(6));
        
        // Adding/subtracting minutes
        System.out.println("Minus 40 minutes    : " + duration.minusMinutes(40));
        System.out.println("Plus 15 minutes     : " + duration.plusMinutes(15));
        
        // Adding/subtracting seconds
        System.out.println("Minus 30 seconds    : " + duration.minusSeconds(30));
        System.out.println("Plus 20 seconds     : " + duration.plusSeconds(20));
        
        // Adding/subtracting Nanos
        System.out.println("Minus 3000 millis   : " + duration.minusMillis(3000));
        System.out.println("Plus 5000 nanos     : " + duration.plusMillis(5000));
        
        // Adding/subtracting Nanos
        System.out.println("Minus 20000 nanos   : " + duration.minusNanos(20000));
        System.out.println("Plus 340000 nanos   : " + duration.plusNanos(340000));
        
        // Using DAYS
        System.out.println("30 days before      : " + duration.minus(30, ChronoUnit.DAYS));
        // Using HOURS
        System.out.println("8 hours before      : " + duration.minus(8, ChronoUnit.HOURS));
        // Using MINUTES
        System.out.println("35 minutes before   : " + duration.minus(35, ChronoUnit.MINUTES));
        // Using SECONDS
        System.out.println("125 seconds later   : " + duration.plus(125, ChronoUnit.SECONDS));
        // Using MILLIS
        System.out.println("7500 millis later   : " + duration.plus(7500, ChronoUnit.MILLIS));
        // Using NANOS
        System.out.println("42357500 nanos later: " + duration.plus(42357500, ChronoUnit.NANOS));
        
        System.out.println("160 minutes before  : " + duration.minus(Duration.ofMinutes(160)));
        System.out.println("3 hours later       : " + duration.plus(Duration.ofHours(3)));
    }
}
                    

Duration            : PT32H15M10.345S
10 days before      : PT-207H-44M-49.655S
15 days later       : PT392H15M10.345S
12 hours before     : PT20H15M10.345S
6 hours later       : PT38H15M10.345S
Minus 40 minutes    : PT31H35M10.345S
Plus 15 minutes     : PT32H30M10.345S
Minus 30 seconds    : PT32H14M40.345S
Plus 20 seconds     : PT32H15M30.345S
Minus 3000 millis   : PT32H15M7.345S
Plus 5000 nanos     : PT32H15M15.345S
Minus 20000 nanos   : PT32H15M10.34498S
Plus 340000 nanos   : PT32H15M10.34534S
30 days before      : PT-687H-44M-49.655S
8 hours before      : PT24H15M10.345S
35 minutes before   : PT31H40M10.345S
125 seconds later   : PT32H17M15.345S
7500 millis later   : PT32H15M17.845S
42357500 nanos later: PT32H15M10.3873575S
160 minutes before  : PT29H35M10.345S
3 hours later       : PT35H15M10.345S

Conclusion

Duration normally used to stored time-based amount between two Instant. If you interested in date-based amount, you need to use Period instead.