Duration ofSeconds() method in Java

Java 8ProgrammingObject Oriented Programming

The duration can be obtained in a one second format using the ofSeconds() method in the Duration class in Java. This method requires two parameters i.e. the number of seconds and the adjustment required in nanoseconds. Also, it returns the duration in a one second format. If the capacity of the duration is exceeded, then the ArithmeticException is thrown.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      long seconds = 515793;
      long adjustment = 100;
      Duration d1 = Duration.ofSeconds(seconds);
      Duration d2 = Duration.ofSeconds(seconds, adjustment);
      System.out.println("The duration without adjustment is: " + d1.getSeconds());
      System.out.println("The duration with adjustment is: " + d2.getSeconds());
   }
}

Output

The duration without adjustment is: 515793
The duration with adjustment is: 515793

Now let us understand the above program.

The duration is obtained in a one second format using the ofSeconds() method and then the duration is printed with and without adjustment using the getSeconds() method. A code snippet that demonstrates this is as follows −

long seconds = 515793;
long adjustment = 100;
Duration d1 = Duration.ofSeconds(seconds);
Duration d2 = Duration.ofSeconds(seconds, adjustment);
System.out.println("The duration without adjustment is: " + d1.getSeconds());
System.out.println("The duration with adjustment is: " + d2.getSeconds());
raja
Published on 13-Mar-2019 11:37:13
Advertisements