Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 498
KunLun Avatar asked Apr 07 '26 00:04

KunLun


2 Answers

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);
like image 53
Zabuzard Avatar answered Apr 08 '26 16:04

Zabuzard


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

like image 43
m.antkowicz Avatar answered Apr 08 '26 16:04

m.antkowicz