@@ -486,23 +486,26 @@ private static Duration create(boolean negate, long daysAsSecs, long hoursAsSecs
486
486
* @throws ArithmeticException if the calculation exceeds the capacity of {@code Duration}
487
487
*/
488
488
public static Duration between (Temporal startInclusive , Temporal endExclusive ) {
489
- try {
489
+ long secs = startInclusive .until (endExclusive , SECONDS );
490
+ if (secs == 0 ) {
491
+ // We don't know which Temporal is earlier, so the adjustment below would not work.
492
+ // But we do know that there's no danger of until(NANOS) overflowing in that case.
490
493
return ofNanos (startInclusive .until (endExclusive , NANOS ));
491
- } catch (DateTimeException | ArithmeticException ex ) {
492
- long secs = startInclusive .until (endExclusive , SECONDS );
493
- long nanos ;
494
- try {
495
- nanos = endExclusive .getLong (NANO_OF_SECOND ) - startInclusive .getLong (NANO_OF_SECOND );
496
- if (secs > 0 && nanos < 0 ) {
497
- secs ++;
498
- } else if (secs < 0 && nanos > 0 ) {
499
- secs --;
500
- }
501
- } catch (DateTimeException ex2 ) {
502
- nanos = 0 ;
503
- }
504
- return ofSeconds (secs , nanos );
505
494
}
495
+ long nanos ;
496
+ try {
497
+ nanos = endExclusive .getLong (NANO_OF_SECOND ) - startInclusive .getLong (NANO_OF_SECOND );
498
+ } catch (DateTimeException ex2 ) {
499
+ nanos = 0 ;
500
+ }
501
+ if (nanos < 0 && secs > 0 ) {
502
+ // ofSeconds will subtract one even though until(SECONDS) already gave the correct
503
+ // number of seconds. So compensate. Similarly for the secs < 0 case below.
504
+ secs ++;
505
+ } else if (nanos > 0 && secs < 0 ) {
506
+ secs --;
507
+ }
508
+ return ofSeconds (secs , nanos );
506
509
}
507
510
508
511
//-----------------------------------------------------------------------
0 commit comments