Signup/Sign In
LAST UPDATED: OCTOBER 22, 2019

How to convert Duration object values to Seconds

    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:

    1. This class was introduced in Java 1.8.

    2. It is immutable and thread-safe.

    3. The class extends Object class and implements Serializable, Comparable<Duration> and TemporalAmount interface.

    4. It is present in java.time package.

    5. The length of the duration is stored using two fields: seconds and nanoseconds.

    6. 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. smiley

    Howdy, I’m Rohit. I’m a software engineer living in Indore, Madhya Pradesh, India. I am a fan of technology, reading, and programming. I’m also interested in fitness and innovation. Sincere By Nature. Cricket Fan By Birth....! :)
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS