Java Convert Nanoseconds to Duration

Tags: Java Duration Java 8

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

How to convert nanoseconds to Duration in Java

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

ConvertNanosecondsToDurationExample1.java

import java.time.Duration;

public class ConvertNanosecondsToDurationExample1 {
    public static void main(String... args) {
        long numberOfNanoseconds = 999888777;

        // Convert number of nanoseconds to Duration
        Duration duration = Duration.ofNanos(numberOfNanoseconds);

        System.out.println("Number of nanoseconds: " + numberOfNanoseconds);
        System.out.println("Duration: " + duration);
    }
}
The output as below.
Number of nanoseconds: 999888777
Duration: PT0.999888777S

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 String to Duration

Java Convert Duration to Seconds