如果我理解正确,使用System.nanoTime()是一种比System.currentTimeInMillis()更准确地保持当前时间标记的方法,即使系统时间已更改.那么为什么当我将nanoTime()的long值转换为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)); }}
解决方法:
System.nanotime() javadoc建议:
返回最精确的可用系统计时器的当前值,以纳秒为单位.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provIDes nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
For example, to measure how long some code takes to execute:
long startTime = System.nanoTime();// ... the code being measured ...long estimatedTime = System.nanoTime() - startTime;
总结 以上是内存溢出为你收集整理的java – 为什么将System.nanoTime()转换为Calendar对象会给我错误的当前日期?全部内容,希望文章能够帮你解决java – 为什么将System.nanoTime()转换为Calendar对象会给我错误的当前日期?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)