Java Instant Instant汇总到下一秒



使用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 nansecond进行比较,但请留下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.
    }

您可以使用lambda函数编程流方法使其成为一个衬里。

添加第二个并截断。要涵盖恰好在一秒钟的角案件的情况

Instant myRoundedUpInstant = Optional.of(myInstant.truncatedTo(ChronoUnit.SECONDS))
                .filter(myInstant::equals)
                .orElse(myInstant.truncatedTo(ChronoUnit.SECONDS).plusSeconds(1));

请参阅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);

请参阅此代码在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,如果Optional不是您的事: - (

最新更新