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 Duration object having 5 seconds and 100 nanoseconds.
  • In line 8, we print the seconds part of the Duration object created in line 7 with the help of get() method with ChronoUnit.SECONDS as the unit of time.
  • In line 9, we print the nanoseconds part of the Duration object created in line 7 with the help of get() method with ChronoUnit.NANOS as the unit of time.

Free Resources