Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | ofSeconds() Method with Example
Duration Class ofSeconds() method: Here, we are going to learn about the ofSeconds() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020
Duration Class ofSeconds() method
Syntax:
public static Duration ofSeconds(long sec_val);
public static Duration ofSeconds(long sec_val, long nanos_adjust);
- ofSeconds() method is available in java.time package.
- ofSeconds(long sec_val) method is used to generate a Duration that represents the given seconds.
- ofSeconds(long sec_val, long nanos_adjust) method is used to generate a Duration that represents the given seconds and adjust in the given nanoseconds if exceeds.
- These methods may throw an exception at the time of representing duration in seconds.
ArithmeticException: This exception may throw when the length of this Duration is less than the given seconds.
- These are static methods and it is accessible with the class name and if we try to access these methods with the class object then we will not get an error.
Parameter(s):
-
In the first case, ofSeconds(long sec_val),
- long sec_val – represents the number of seconds of the returned Duration.
-
In the first case, ofSeconds(long sec_val, long nanos_adjust),
- long sec_val – represents the number of seconds of the returned Duration.
- long nanos_adjust – represents the nanoseconds adjust to the given number of seconds.
Return value:
In both the cases, the return type of the method is Duration,
- In the first case, it returns the Duration that represents the given number of seconds.
- In the second case, it returns the Duration that represents the given seconds and adjusts in the given nanoseconds.
Example:
// Java program to demonstrate the example
// of ofSeconds() method of Duration
import java.time.*;
public class OfSecondsDuration {
public static void main(String args[]) {
long sec = 10;
long nanos_adjust = 20000;
// returns the Duration that holds the
// value of the given seconds
Duration du_sec = Duration.ofSeconds(sec);
// Display du_sec
System.out.println("Duration.ofSeconds(sec): " + du_sec);
// returns the Duration that holds the
// value of the given seconds and adjusted
// in nanoseconds
du_sec = Duration.ofSeconds(sec, nanos_adjust);
// Display du_sec
System.out.println("Duration.ofSeconds(sec,nanos_adjust): " + du_sec);
}
}
Output
Duration.ofSeconds(sec): PT10S
Duration.ofSeconds(sec,nanos_adjust): PT10.00002S