Java Convert Seconds to Duration

Tags: Java Duration Java 8

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

How to convert seconds to Duration in Java

In Java, we can use the Duration.ofSeconds(long seconds) static method to instantiate a Duration object from number of seconds as the example Java code below.

ConvertSecondsToDurationExample1.java

import java.time.Duration;

public class ConvertSecondsToDurationExample1 {
    public static void main(String... args) {
        long numberOfSeconds = 345000;

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

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

In the following example Java code we show how to convert number of seconds and nanoseconds to Duration object using the Duration.ofSeconds(long seconds, long nanoAdjustment) static method.

ConvertSecondsToDurationExample2.java

import java.time.Duration;

public class ConvertSecondsToDurationExample2 {
    public static void main(String... args) {
        long numberOfSeconds = 345000;
        long nanos = 111222333;

        // Convert number of seconds and nanoseconds to Duration
        Duration duration = Duration.ofSeconds(numberOfSeconds, nanos);

        System.out.println("Number of seconds: " + numberOfSeconds);
        System.out.println("Nanoseconds: " + nanos);
        System.out.println("Duration: " + duration);
    }
}
The output as below.
Number of seconds: 345000
Nanoseconds: 111222333
Duration: PT95H50M0.111222333S

Happy Coding 😊

Java Convert Days to Duration

Java Convert Hours to Duration

Java Convert Minutes to Duration

Java Convert Milliseconds to Duration

Java Convert Nanoseconds to Duration

Java Convert String to Duration

Java Convert Duration to Seconds