在Instant
中有方法:
-
toEpochMilli
将这个瞬间转换为从 1970-01-01T00:00:00Z 开始的毫秒数 -
getEpochSecond
从 1970-01-01T00:00:00Z 的 Java 时代获取秒数。
这两种方法都会失去精度,例如在 toEpochMilli
JavaDoc 中我看到:
If this instant has greater than millisecond precision, then the conversion drop any excess precision information as though the amount in nanoseconds was subject to integer division by one million.
我没有看到相应的方法来获得更精确的时间戳。 如何从 Java 8 中的纪元获取微米或纳米的数量?
最佳答案
将 getNano()
与 getEpochSeconds()
一起使用。
int getNano()
Gets the number of nanoseconds, later along the time-line, from the start of the second. The nanosecond-of-second value measures the total number of nanoseconds from the second returned by
getEpochSecond
.
使用 TimeUnit
转换为所需的单位,如评论所建议的:
Instant inst = Instant.now();
// Nano seconds since epoch, may overflow
long nanos = TimeUnit.SECONDS.toNanos(inst.getEpochSecond()) + inst.getNano();
// Microseconds since epoch, may overflow
long micros = TimeUnit.SECONDS.toMicros(inst.getEpochSecond()) + TimeUnit.NANOSECONDS.toMicros(inst.getNano());
您还可以找出它们何时溢出:
// 2262-04-11T23:47:16.854775807Z
Instant.ofEpochSecond(TimeUnit.NANOSECONDS.toSeconds(Long.MAX_VALUE),
Long.MAX_VALUE % TimeUnit.SECONDS.toNanos(1));
// +294247-01-10T04:00:54.775807Z
Instant.ofEpochSecond(TimeUnit.MICROSECONDS.toSeconds(Long.MAX_VALUE),
TimeUnit.MICROSECONDS.toNanos(Long.MAX_VALUE % TimeUnit.SECONDS.toMicros(1)))
关于java - 将 Instant 从大纪元时间转换为微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47869659/