8307466: java.time.Instant calculation bug in until and between methods

Co-authored-by: Raffaello Giulietti <rgiulietti@openjdk.org>
Reviewed-by: scolebourne, naoto
This commit is contained in:
Roger Riggs 2023-05-09 20:51:33 +00:00
parent 723582c524
commit 356667f155
2 changed files with 78 additions and 8 deletions

View file

@ -1169,20 +1169,30 @@ public final class Instant
}
private long microsUntil(Instant end) {
long secsDiff = Math.subtractExact(end.seconds, seconds);
long totalMicros = Math.multiplyExact(secsDiff, MICROS_PER_SECOND);
return Math.addExact(totalMicros, (end.nanos - nanos) / 1000);
long microsDiff = Math.multiplyExact(end.seconds - seconds, MICROS_PER_SECOND);
int nanosDiff = end.nanos - nanos;
if (microsDiff > 0 && nanosDiff < 0) {
return (microsDiff - 1_000_000) + (nanosDiff + 1_000_000_000) / 1_000;
} else if (microsDiff < 0 && nanosDiff > 0) {
return (microsDiff + 1_000_000) + (nanosDiff - 1_000_000_000) / 1_000;
}
return Math.addExact(microsDiff, nanosDiff / 1_000);
}
private long millisUntil(Instant end) {
long secsDiff = Math.subtractExact(end.seconds, seconds);
long totalMillis = Math.multiplyExact(secsDiff, MILLIS_PER_SECOND);
return Math.addExact(totalMillis, (end.nanos - nanos) / 1000_000);
long millisDiff = Math.multiplyExact(end.seconds - seconds, MILLIS_PER_SECOND);
int nanosDiff = end.nanos - nanos;
if (millisDiff > 0 && nanosDiff < 0) {
return (millisDiff - 1_000) + (nanosDiff + 1_000_000_000) / 1_000_000;
} else if (millisDiff < 0 && nanosDiff > 0) {
return (millisDiff + 1_000) + (nanosDiff - 1_000_000_000) / 1_000_000;
}
return Math.addExact(millisDiff, nanosDiff / 1_000_000);
}
private long secondsUntil(Instant end) {
long secsDiff = Math.subtractExact(end.seconds, seconds);
long nanosDiff = end.nanos - nanos;
int nanosDiff = end.nanos - nanos;
if (secsDiff > 0 && nanosDiff < 0) {
secsDiff--;
} else if (secsDiff < 0 && nanosDiff > 0) {