我想以“秒”:“纳秒”的格式获得kotlin的TAI时间戳。
这是我目前的解决方案,我相信会有更好的方法来实现这一点,
import java.time.Instant
import java.time.temporal.ChronoUnit;
fun main() {
val epochNanoseconds = ChronoUnit.NANOS.between(Instant.EPOCH, Instant.now())
val epochSeconds = epochNanoseconds/1000000000
val remainingNanoSeconds = (epochNanoseconds.toDouble()/1000000000 - epochSeconds).toString().split(".")[1]
println("$epochSeconds:$remainingNanoSeconds")
}示例输出:
1670190945:027981042861938477是否有任何方法可以直接从java.time.Instant或任何其他库获得秒和剩余的纳秒来方便地实现这一点?
我认为即使我的解决方案也不完全正确。
val remainingNanoSeconds = (epochNanoseconds.toDouble()/1000000000 - epochSeconds).toString().split(".")[1]这给了我秒,而不是纳秒。
发布于 2022-12-04 22:10:08
是的,您可以使用Instant类的toEpochMilli()方法获得自纪元开始以来作为长值的毫秒数。然后,可以使用这个长值来计算剩余的秒数和纳秒数。下面的示例演示如何做到这一点:
爪哇:
long epochMilli = Instant.now().toEpochMilli();
long secondsRemaining = epochMilli / 1000;
long nanosecondsRemaining = (epochMilli % 1000) * 1000000;
System.out.println("Seconds remaining: " + secondsRemaining);
System.out.println("Nanoseconds remaining: " + nanosecondsRemaining);科特林:
val epochMilli = Instant.now().toEpochMilli()
val secondsRemaining = epochMilli / 1000
val nanosecondsRemaining = (epochMilli % 1000) * 1000000
println("Seconds remaining: $secondsRemaining")
println("Nanoseconds remaining: $nanosecondsRemaining")https://stackoverflow.com/questions/74681344
复制相似问题