What is Duration.of() in Java?
Overview
of() is a Duration class. It is used to obtain a Duration object given the amount of duration and the specified unit of duration.
The of 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 static Duration of(long amount, TemporalUnit unit)
Parameters
long amount: The amount of the duration. The value can be positive or negative.TemporalUnit unit: The unit in which the duration is measured.
Return value
This method returns a Duration object.
Code
import java.time.Duration;import java.time.temporal.ChronoUnit;import java.time.temporal.TemporalUnit;public class Main {public static void main(String[] args){long durationAmount = 10;TemporalUnit temporalUnit = ChronoUnit.DAYS;Duration duration = Duration.of(durationAmount, temporalUnit);System.out.println("Duration object - " + duration);}}
Explanation
- Lines 1–3: We import the relevant packages.
- Line 8: We define the amount of the duration.
- Line 9: We define the unit of measurement of the duration.
- Line 10: We create a
Durationobject using theof()method by passing thedurationAmountandtemporalUnitas arguments. - Line 11: We print the
Durationobject created in line 10.