How to Convert System.nanoTime to Seconds in Java


In this example we will show how to convert nanoTime to seconds.

Source Code

package com.beginner.examples;

import java.util.concurrent.TimeUnit;

public class NanoTime2SecondsExample {

    public static void main(String[] args) throws InterruptedException{
    	
    	long nano1 = System.nanoTime();

        Thread.sleep(2000);

        long nano2 = System.nanoTime();

        long nano = nano2 - nano1;

        System.out.println("There are " + nano + " nano.");

        // 1 second = 1000000000 nano
        double second = (double) nano / 1000000000;

        System.out.println("There are " + second + " seconds.");

        // TimeUnit.SECONDS.convert
        long secondTime = TimeUnit.SECONDS.convert(nano, TimeUnit.NANOSECONDS);

        System.out.println("There are " + secondTime + " seconds.");
    }
}

Output:

There are 2000104833 nano.
There are 2.000104833 seconds.
There are 2 seconds.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments