Instant plus with negative values

I have this code

Instant now = Instant.now();
if (amountDays >= 0) {
    now = now.plus(amountDays, ChronoUnit.DAYS);
} else {
    now = now.minus(Math.abs(amountDays), ChronoUnit.DAYS);
}

And I was thinking to simplify it like this

Instant now = Instant.now();
now = now.plus(amountDays, ChronoUnit.DAYS);

However, I am unsure if plus works correctly with negative values or if that messes up the result.

Can I use plus like that, with possibly negative values?

Answer

plus with negative values

The plus method supports adding negative times to go back in time, from its documentation:

amountToAdd – the amount of the unit to add to the result, may be negative

So all good, you can use it like that and it will work as expected.


Implementation

Little trivia, the current implementation of minus even delegates to plus with -amountToSubtract as value:

return (amountToSubtract == Long.MIN_VALUE
    ? plus(Long.MAX_VALUE, unit).plus(1, unit)
    : plus(-amountToSubtract, unit));

Notes

In general, if you just want to go back in time, prefer using minus for readability.

In your particular case I would stick with just plus though to not bloat the code and logic unecessarily. Instead, prefer adding a comment

// amountDays may be negative

or ensure that your javadoc is clear about that.

Minor improvement, you can simplify your code from two statements to just one:

Instant now = Instant.now().plus(amountDays, ChronoUnit.DAYS);

Leave a Reply

Your email address will not be published. Required fields are marked *