java - System.currentTimeMillis()、new Date().getTime() 和 Calendar.getInstance().getTimeInMillis() 的准确性?

标签 java date calendar

我正要在 Eclipse 中使用 System.currentTimeMillis() 时,我注意到它的 Javadoc 中出现了以下段落:

Returns the current system time in milliseconds since January 1, 1970
00:00:00 UTC. This method shouldn't be used for measuring timeouts or
other elapsed time measurements, as changing the system time can affect
the results.

所以这意味着如果我想专门维护对当前时间点的引用,我不能依赖 System.currentTimeMillis()。那么,最准确的方法是什么?这三种方法标记当前时间是否不同?

更新:我想做的是测量两个独立程序运行中两个时间点之间的差异。我担心的是,如果我使用 System.currentTimeMillis() 并且用户在第一次运行后使用系统时间,我可能会在第二次运行时得到一个奇怪的意外值。

最佳答案

您应该使用 API 文档中的 System.nanoTime():

Returns the current value of the most precise available system timer, in nanoseconds.

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.

关于java - System.currentTimeMillis()、new Date().getTime() 和 Calendar.getInstance().getTimeInMillis() 的准确性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158307/

相关文章:

java - 将一个网格布局分成两部分

java - Android:如何以用户的语言获取当前的星期几(星期一等)?

java - 日期解析魔法

java - 如何将 ISO 8601 日期(字符串)转换为日期?

php - 从数据库获取事件到日历页面

java - java.util.logging.Filehandler 更改输出文件时调用方法

java - 使用 GRADLEW BUILD 运行时如何在每个测试类之间删除 H2 数据库?

java - 将 smooks 1.4 升级到 1.5 会破坏 CSV 解析(空输入)

html - 如何在 Firefox 中隐藏 <input type ="date"> 的弹出日历?

google-api - Google Calendar API V3 insert_calendar 返回 503,但日历插入成功