What is Duration.from() in Java?
Overview
from() is a static method of the Duration class. It is used to obtain an instance of the Duration class based on the provided TemporalAmount.
A TemporalAmount represents an amount of time that may be date-based or time-based.
Check the following import statement to import the Duration class.
import java.time.Duration;
Syntax
public static Duration from(TemporalAmount amount)
Parameters
TemporalAmount amount: The amount of time to convert.
Return value
This method returns a new Duration object.
Example
import java.time.Duration;import java.time.temporal.ChronoUnit;public class Main {public static void main(String[] args){Duration duration = Duration.from(ChronoUnit.HOURS.getDuration());System.out.println("Duration object - " + duration);}}
Explanation
- Lines 1–2: We import the relevant packages.
- Line 7: We create a
Durationobject using thefrom()method. - Line 8: We print the
Durationobject created in line 7.