gpt4 book ai didi

Java Instant 舍入到下一秒

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:05:11 25 4
gpt4 key购买 nike

使用 Java Instant 类,如何舍入到最接近的秒数?不管是1毫秒、15毫秒还是999毫秒,都应该四舍五入到下一秒0毫秒。

我基本上想要,

Instant myInstant = ...

myInstant.truncatedTo(ChronoUnit.SECONDS);

但方向相反。

最佳答案

您可以使用 .getNano 来覆盖极端情况,以确保时间在秒上不完全均匀,然后使用 .plusSeconds() 添加额外的秒当有值要截断时。

    Instant myInstant = Instant.now();
if (myInstant.getNano() > 0) //Checks for any nanoseconds for the current second (this will almost always be true)
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
}
/* else //Rare case where nanoseconds are exactly 0
{
myInstant = myInstant;
} */

我留在 else 语句中只是为了演示如果正好是 0 纳秒则不需要执行任何操作,因为没有理由不截断任何内容。

编辑:如果您想检查时间是否至少为 1 毫秒以进行四舍五入,而不是 1 纳秒,您可以将它与 1000000 纳秒进行比较,但保留 else 语句截断纳秒:

    Instant myInstant = Instant.now();
if (myInstant.getNano() > 1000000) //Nano to milliseconds
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1);
}
else
{
myInstant = myInstant.truncatedTo(ChronoUnit.SECONDS); //Must truncate the nanoseconds off since we are comparing to milliseconds now.
}

关于Java Instant 舍入到下一秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57274205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com