Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | from() Method with Example
Duration Class from() method: Here, we are going to learn about the from() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 14, 2020
Duration Class from() method
- from() method is available in java.time package.
- from() method is used to return a copy of this Duration from the given TemporalAmount.
- from() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
- from() method may throw an exception at the time of returning Duration from the given amount.
- DateTimeException: This exception may throw when the given amt couldn't convert into a Duration.
- ArithmeticException: This exception may throw when the calculated exceeds the limit.
Syntax:
public static Duration from(TemporalAmount amt);
Parameter(s):
- TemporalAmount amt – represents the amount to convert to a Duration.
Return value:
The return type of this method is Duration, it returns the Duration that is calculated from the given amount.
Example:
// Java program to demonstrate the example
// of Duration from(TemporalAmount amt) method of Duration
import java.time.*;
public class FromOfDuration {
public static void main(String args[]) {
// Instantiates a Duration object
Duration du1 = Duration.ofHours(10);
// Display du1
System.out.println("du1: " + du1);
// returns an instance of
// Duration from the given temporal
// amount i.e. here the given amount is
// 10 hrs so it generates a new Duration
// (du_from) for the given amount
Duration du_from = Duration.from(du1);
// Display du_from
System.out.println("du_from: " + du_from);
// Here, we are converting 10 hrs into Minutes
System.out.println("du_from.toMinutes(): " + du_from.toMinutes());
// Here, we are converting 10 hrs into Seconds
System.out.println("du_from.toSeconds(): " + du_from.toSeconds());
}
}
Output
du1: PT10H
du_from: PT10H
du_from.toMinutes(): 600
du_from.toSeconds(): 36000