There are a series of methods that add or subtract a unit from a duration. Since the Duration object is immutable, the return value is a new Duration object. Table 9 – Duration minus Method Summary and Table 10 – Duration add Method Summary summarizes these methods. Table 9 – Duration minus Method Summary Method | Argument minus | Duration duration minus | long amountToSubtract, TemporalUnit unit minusDays | long daysToSubtract minusHours | long hoursToSubtract minusMillis | long millisToSubtract minusMinutes | long minutesToSubtract minusNanos | long nanosToSubtract minusSeconds | long secondsToSubtract subtractFrom | Temporal temporal
Table 10 – Duration add Method Summary Method | Argument plus | Duration duration plus | long amountToAdd, TemporalUnit unit plusDays | long daysToAdd plusHours | long hoursToAdd plusMillis | long millisToAdd
plusMinutes | long minutesToAdd plusNanos | long nanosToAdd plusSeconds | long secondsToAdd addTo | Temporal temporal A duration is created, below, based on an initial duration of 30 minutes. Ten seconds is then added to it and then 500 milliseconds is subtracted from it. Duration duration = Duration.ofMinutes(30).
plus(Duration.ofSeconds(10)). minus(Duration.ofMillis(500)); System.out.println(duration); The resulting duration is shown below: PT30M9.5S
Using the Duration Class The Duration class supports getter methods as listed in Table 11 – Duration Class get Type Methods. Table 11 – Duration Class get Type Methods Return Type | Method | Meaning int | getNano() | The number of nanoseconds since the last second long | getSeconds() | The length of the Duration in seconds boolean | isNegative() | Returns true if the Duration is negative boolean | isZero() | Returns true if the Duration’s length is zero In addition, it supports a number of methods that manipulate a Duration instance. The following demonstrates calculating 2/3 of the time between two dates. The between method returns the initial duration. The multipliedBy and dividedBy
methods compute the fractional part of this duration. LocalTime time1 = LocalTime.of(10, 30); LocalTime time2 = LocalTime.of(11, 45); duration = Duration.between(time1, time2). multipliedBy(2). dividedBy(3); System.out.println(duration); The result is shown below: PT50M