有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java查找历元和当前时间之间的时差

当使用系统获取其中一个时间值时,我需要找到两个时间值之间的差异。currentTimeMillis()即它是the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC,另一个是使用系统获取的。nanoTime()表示它是current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds

我该怎么做


共 (2) 个答案

  1. # 1 楼答案

    这是不可能的。你对纳米时代及其目的有误解

    the documentation

    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.

  2. # 2 楼答案

    你无法比较它们;它们是苹果和桔子,不是在同一个尺度上测量的,也不是在同一个时间点上测量的。特别是,虽然自1970年1月1日00:00:00Z起currentTimeMillis()是毫秒,但nanoTime()是从。。。嗯,可能是您的机器、JVM或任何东西的启动时间

    如果您同时调用这两个方法并记录相关性,那么以后可以进行类似的相关性,但这是唯一的方法,不能保证精确