Java Convert Duration to Seconds

Tags: Java Duration Java 8

In this Java core tutorial we learn how to convert a java.time.Duration object to number of seconds in Java programming language.

How to convert Duration to Seconds in Java

In Java, with a given Duration object we can use the Duration.getSeconds() method to get number of seconds as the example Java code below.

ConvertDurationToSecondsExample1.java

import java.time.Duration;

public class ConvertDurationToSecondsExample1 {
    public static void main(String... args) {
        // PT5M equals 5 minutes
        Duration duration = Duration.parse("PT5M");

        // Convert Duration to number of seconds
        long numberOfSeconds = duration.getSeconds();

        System.out.println("Duration: " + duration);
        System.out.println("Number of seconds: " + numberOfSeconds);
    }
}
The output as below.
Duration: PT5M
Number of seconds: 300

Happy Coding 😊

Java Convert Days to Duration

Java Convert Hours to Duration

Java Convert Minutes to Duration

Java Convert Seconds to Duration

Java Convert Milliseconds to Duration

Java Convert Nanoseconds to Duration

Java Convert String to Duration