Java – How to convert System.nanoTime to Seconds

We can just divide the nanoTime by 1_000_000_000, or use the TimeUnit.SECONDS.convert to convert it.

Note
1 second = 1_000_000_000 nanosecond
JavaExample.java

package com.mkyong;

import java.util.concurrent.TimeUnit;

public class JavaExample {

    public static void main(String[] args) throws InterruptedException {

        long start = System.nanoTime();

        Thread.sleep(5000);

        long end = System.nanoTime();

        long elapsedTime = end - start;

        System.out.println(elapsedTime);

        // 1 second = 1_000_000_000 nano seconds
        double elapsedTimeInSecond = (double) elapsedTime / 1_000_000_000;

        System.out.println(elapsedTimeInSecond + " seconds");

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

        System.out.println(convert + " seconds");

    }

}

Output


5000353564
5.000353564 seconds
5 seconds

References

  1. Wikipedia – Nanosecond
  2. TimeUnit Javadoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar