What is Duration.get() in Java?
The get() is an instance method of the Duration class which is used to get the seconds and nanosecond part of the Duration object.
Any other units of time throw an exception.
The get() method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class check the following import statement.
import java.time.Duration;
Syntax
public long get(TemporalUnit unit)
Parameters
TemporalUnit unit: The unit for which to return the value.
Return value
This method returns the long value of the specified unit.
Code
import java.time.Duration;import java.time.temporal.ChronoUnit;public class Main{public static void main(String[] args) {Duration duration = Duration.ofSeconds(5, 100);System.out.printf("Seconds in %s - %s", duration, duration.get(ChronoUnit.SECONDS));System.out.println();System.out.printf("Nanoseconds in %s - %s", duration, duration.get(ChronoUnit.NANOS));}}
Explanation
- In lines 1 and 2, we import the relevant packages.
- In line 7, we define a
Durationobject having5seconds and100nanoseconds. - In line 8, we print the seconds part of the
Durationobject created in line 7 with the help ofget()method withChronoUnit.SECONDSas the unit of time. - In line 9, we print the nanoseconds part of the
Durationobject created in line 7 with the help ofget()method withChronoUnit.NANOSas the unit of time.