This method returns the value of the specified temporal unit. If the provided TemporalUnit is not supported, UnsupportedTemporalTypeException will be thrown.
package com.logicbig.example.duration;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
public class GetExample {
public static void main(String... args) {
Duration d = Duration.between(LocalDate.now().atStartOfDay(), LocalDateTime.now());
for (ChronoUnit unit : ChronoUnit.values()) {
try {
long l = d.get(unit);
System.out.printf("%10s: %s%n", unit.name(), l);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf("%10s: %s%n", unit.name(), e.getMessage());
}
}
}
}
Output
NANOS: 961000000
MICROS: Unsupported unit: Micros
MILLIS: Unsupported unit: Millis
SECONDS: 57570
MINUTES: Unsupported unit: Minutes
HOURS: Unsupported unit: Hours
HALF_DAYS: Unsupported unit: HalfDays
DAYS: Unsupported unit: Days
WEEKS: Unsupported unit: Weeks
MONTHS: Unsupported unit: Months
YEARS: Unsupported unit: Years
DECADES: Unsupported unit: Decades
CENTURIES: Unsupported unit: Centuries
MILLENNIA: Unsupported unit: Millennia
ERAS: Unsupported unit: Eras
FOREVER: Unsupported unit: Forever
Using Duration#get() with Duration#getUnits():
package com.logicbig.example.duration;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalUnit;
public class GetExample2 {
public static void main(String... args) {
Duration d = Duration.between(LocalDate.now().atStartOfDay(), LocalDateTime.now());
System.out.println(d);
for (TemporalUnit unit : d.getUnits()) {
long l = d.get(unit);
System.out.printf("%10s: %s%n", unit, l);
}
}
}
Output
PT15H59M32.973S
Seconds: 57572
Nanos: 973000000