Calling the JDKs Instant.toEpochMilli()
could result in an arithmetic overflow/underflow (e.g. Instant.MAX.toEpochMilli()
or Instant.MIN.toEpochMilli()
). I am looking for a simple way to avoid the arithmetic overflow and simply use Long.MAX_VALUE
. Here's my current code.
long seconds, millis;
seconds = deadline.getEpochSecond();
if (seconds > Long.MAX_VALUE / 1000 - 1)
millis = Long.MAX_VALUE;
else if (seconds < Long.MIN_VALUE / 1000 + 1)
millis = Long.MIN_VALUE;
else
millis = deadline.toEpochMilli();
It seems like there has to be a cleaner/clearer way to implement this. How would you implement this logic?
I have to be concerned about overflow/underflow because Instant.MAX
and Instant.MIN
are passed to the method where this code resides.