What is Duration.ofSeconds() in Java?
ofSeconds() is a Duration class that is used to get a Duration instance representing the number of seconds.
The ofSeconds 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 ofSeconds(long seconds)
Parameters
long seconds: The number of seconds. It can be positive or negative.
Return value
The method returns a Duration object.
Code
In the code below, we create two Duration class objects with a positive and negative number of seconds. Then we print the objects to the console.
import java.time.Duration;public class Main{public static void main(String[] args) {Duration positiveSeconds = Duration.ofSeconds(5);System.out.println("Positive Seconds - " + positiveSeconds);Duration negativeSeconds = Duration.ofSeconds(-5);System.out.println("Negative Seconds - " + negativeSeconds);}}
Note: The output is in the ISO 8601 duration format.