对比System.currentTimeMillis()、new Date().getTime()、System.nanoTime()

1.System.currentTimeMillis()和new Date().getTime()

开发时习惯使用new Date().getTime()来获取当前的毫秒数,但其实没有必要
java中Date的代码实现:

public Date()
{
...
this(System.currentTimeMillis());
}

new Date()做的事情就是调用System.currentTimeMillis(),两者本质上效果一样,所以建议使用System.currentTimeMillis()代替new Date().getTime(),同时效率也更高


2.System.currentTimeMillis()和System.nanoTime()

System.currentTimeMillis()返回的是自1970年1月1日0时起的毫秒数
System.nanoTime()返回的是纳秒值可能是任意时间或者是负数
System.nanoTime()主要用于计算时间间隔,精度较高
示例:

long t0 = System.nanoTime();
// do something
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("something took: %d ms", millis));

猜你喜欢

转载自www.cnblogs.com/hu-hugh/p/dui-bisystemcurrenttimemillisnew-dategettimesystem.html
今日推荐