Java Instant向上舍入到下一秒

rya*_*694 3 java java-time

使用Java Instant类,如何舍入到最接近的秒?我不在乎是1毫秒,15毫秒还是999毫秒,所有数值都应以0毫秒舍入到下一秒。

我基本上想要

Instant myInstant = ...

myInstant.truncatedTo(ChronoUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

但方向相反。

Nex*_*vis 5

您可以通过使用.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;
    } */
Run Code Online (Sandbox Code Playgroud)

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

编辑: 如果您想检查时间是否至少要超过一毫秒以进行舍入,而不是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.
    }
Run Code Online (Sandbox Code Playgroud)


Mic*_*rry 5

您可以使用lambda 函数式编程流方法使其成为单行程序。

添加第二个并截断。要覆盖精确到一秒钟的极端情况,请检查截断到原始的情况,如果它们不同,则只添加一秒钟:

Instant myRoundedUpInstant = Optional.of(myInstant.truncatedTo(ChronoUnit.SECONDS))
                .filter(myInstant::equals)
                .orElse(myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));
Run Code Online (Sandbox Code Playgroud)

请参阅IdeOne.com 上的代码运行行

Instant.toString(): 2019-07-30T20:06:33.456424Z

myRoundedUpInstant(): 2019-07-30T20:06:34Z

…和…

myInstant.toString(): 2019-07-30T20:05:20Z

myRoundedUpInstant(): 2019-07-30T20:05:20Z

或者,使用稍微不同的方法:

Instant myRoundedUpInstant = Optional.of(myInstant)
        .filter(t -> t.getNano() != 0)
        .map(t -> t.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1))
        .orElse(myInstant);
Run Code Online (Sandbox Code Playgroud)

查看此代码在 IdeOne.com 上实时运行

myInstant.toString(): 2019-07-30T20:09:07.415043Z

myRoundedUpInstant(): 2019-07-30T20:09:08Z

…和…

myInstant.toString(): 2019-07-30T19:44:06Z

myRoundedUpInstant(): 2019-07-30T19:44:06Z

以上当然是在 Java 8 领域。我将把它留给读者作为练习,把它分成更传统的 if/else ifOptional不是你的东西:-)

  • 从“Optional”开始来固定流的一个很好的例子。我对此一无所知。谢谢。 (2认同)