Java - System.nanoTimeを秒に変換する方法

nanoTimeを 1 000 000__000`で分割するか、 TimeUnit.SECONDS.convert`を使って変換します。

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");

    }

}

出力

5000353564
5.000353564 seconds
5 seconds