3

如果我理解正确,即使系统时间已更改, usingSystem.nanoTime()也是一种将标记保持在当前时间的更准确方法。System.currentTimeInMillis()那么为什么当我将 long 值转换为nanoTime()对象Calendar时,输出是错误的呢?

import java.util.Calendar;

public class Test {

    public static void main(String[] args) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        System.out.println(c.get(Calendar.MONTH) + " " + c.get(Calendar.DATE) + " " + c.get(Calendar.YEAR) +
                " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND)
                + ":" + c.get(Calendar.MILLISECOND));
    }

}
4

1 回答 1

8

System.nanotime() javadoc 建议:

返回最精确的可用系统计时器的当前值,以纳秒为单位。

此方法只能用于测量经过的时间,与系统或挂钟时间的任何其他概念无关。返回的值表示自某个固定但任意时间以来的纳秒(可能在将来,因此值可能为负数)。此方法提供纳秒精度,但不一定提供纳秒精度。不保证值的变化频率。由于数值溢出,超过大约 292 年(263 纳秒)的连续调用的差异将无法准确计算经过的时间。

例如,要测量一些代码需要多长时间执行:

long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
于 2012-09-10T06:16:20.070 回答