Accessing Time Units in a Duration – Date and Time

Accessing Time Units in a Duration

The Duration class provides the getUNIT() methods to read the individual values of its time units. The class also has methods to check if the period has a negative value or if its value is zero.

Click here to view code image

Duration dx = Duration.ofSeconds(12L*60*60, 500_000_000L); // PT12H0.5S
out.println(dx.getNano());                                 // 500000000
out.println(dx.getSeconds());                              // 43200 (i.e. 12 hrs.)

Reading the individual values of time units of a Duration object can also be done using the get(unit) method, where only the NANOS and SECONDS units are allowed. A list of temporal units that are accepted by the get(unit) method can be obtained by calling the getUnits() of the Duration class.

Click here to view code image

out.println(dx.get(ChronoUnit.NANOS));       // 500000000
out.println(dx.get(ChronoUnit.SECONDS));     // 43200
out.println(dx.get(ChronoUnit.MINUTES));     // UnsupportedTemporalTypeException
out.println(dx.getUnits());                  // [Seconds, Nanos]

The class Duration provides the method toUNIT() to derive the total length of the duration in the unit designated by the method name. The seconds and the nanoseconds are converted to this unit, if necessary.

Click here to view code image

out.println(“Days:    ” + dx.toDays());      // Days:    0
out.println(“Hours:   ” + dx.toHours());     // Hours:   12
out.println(“Minutes: ” + dx.toMinutes());   // Minutes: 720
out.println(“Millis:  ” + dx.toMillis());    // Millis:  43200500
out.println(“Nanos:   ” + dx.toNanos());     // Nanos:   43200500000000

int getNano()
long getSeconds()

Return the number of nanoseconds and seconds in this duration, respectively—not the total length of the duration. Note that the first method name is getNano, without the s.

long get(TemporalUnit unit)

Returns the value of the specified unit in this Duration—not the total length of the duration. The only supported ChronoUnit constants are NANOS and SECONDS (p. 1044). Other units result in an UnsupportedTemporalTypeException.

List<TemporalUnit> getUnits()

Returns the list of time units supported by this duration: NANOS and SECONDS (p. 1044). These time units can be used with the get(unit) method.

long toDays()
long toHours()
long toMinutes()
long toMillis()
long toNanos()

Return the total length of this duration, converted to the unit designated by the method, if necessary. Note that there is no toSeconds() method. Also, the method name is toNanos—note the s at the end.

The methods toMillis() and toNanos() throw an ArithmeticException in case of number overflow.

boolean isNegative()

Determines whether the total length of this duration is negative.

boolean isZero()

Determines whether the total length of this duration is zero.