In this blog, we will see what is Duration class and how to convert the Duration class's object values to seconds. Let's talk about Duration class first then we will see about the conversion.
In the section below we have described the Duration class to make you more comfortable with Duration class:
-
This class was introduced in Java 1.8.
-
It is immutable and thread-safe.
-
The class extends Object class and implements Serializable, Comparable<Duration> and TemporalAmount interface.
-
It is present in java.time package.
-
The length of the duration is stored using two fields: seconds and nanoseconds.
-
This class models the amount of time in terms of seconds and nanoseconds.
I hope, we are now good with what Duration class is. Now, let's jump in with the practical example which will demonstrate the conversion of Duration object to seconds value.
package com.studyTonight;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
/**
* The class is used to demonstrate the conversion of Duration to Seconds.
* @author studyToNight
*
*/
public class DurationToSecondConversion {
/**
* Main method.
* @param args
*/
public static void main(String args[]) {
System.out.println("--- Example ---");
// Create new Duration type variable named as 'hour'.
Duration hour = Duration.ofHours(1);
// It will print number of seconds present in one hour.
System.out.println("Number of seconds present in one hour -> " + hour.getSeconds());
// You can use 'ChronoUnit' as well to take value in Hours, Minutes, Year, etc in Duration type variable.
Duration hour1 = Duration.of(1, ChronoUnit.HOURS);
// It will print number of seconds present in one hour.
System.out.println("Number of seconds present in one hour -> " + hour1.getSeconds());
}
}
Output:
--- Example ---
Number of seconds present in one hour -> 3600
Number of seconds present in one hour -> 3600
You can try runing this code in our Code Playground for Java.
I hope we all are now good with what Duration class is and how this conversion works. Please let us know if you have any concerns/query and we will be happy to assist you.