Duration ofSeconds() method in Java


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());

Updated on: 30-Jul-2019

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements