Java Instant round up to the next second

ryanp102694 :

Using the Java Instant class, how can I round up to the nearest second? I don't care if it is 1 millisecond, 15 milliseconds, or 999 milliseconds, all should round up to the next second with 0 milliseconds.

I basically want,

Instant myInstant = ...

myInstant.truncatedTo(ChronoUnit.SECONDS);

but in the opposite direction.

Nexevis :

You can cover the corner case by using .getNano to make sure the time is not exactly even on the second and then add the extra second using .plusSeconds() when there is a value to truncate.

    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;
    } */

I left in the else statement just to demonstrate no operations need to be done if it is exactly 0 nanoseconds, because there is no reason to truncate nothing.

EDIT: If you want to check if the time is at least 1 millisecond over a second in order to round up, instead of 1 nanosecond you can then compare it to 1000000 nanoseconds but leave the else statement in to truncate the nanoseconds:

    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.
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125751&siteId=1