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?
plus with negative valuesThe 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.
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));
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);
Just take a look how minus is implemented
@Override
public Instant minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
Of course for readability sake it makes sense to use both plus and minus in proper situations but checking whether amountDays is greater or lower from 0 seems to be some kind of internal Instant.plus logic and is deifinitely not helping with readability of your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With