Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8014939

java.time.OffsetDateTime.INSTANT_COMPARATOR.compare() does not return same value with compareTo()

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 8
    • 8
    • core-libs
    • b102
    • Verified

      It looks one bug in java.time.OffsetDateTime. The return value of compareTo() and OffsetDateTime.INSTANT_COMPARATOR.compare() are different.

      Sample code:
      ========
      OffsetDateTime a = OffsetDateTime.of(2008, 6, 30, 11, 20, 40, 4, ZoneOffset.ofHours(2));
      OffsetDateTime b = OffsetDateTime.of(2008, 6, 30, 10, 20, 40, 5, ZoneOffset.ofHours(1));
      System.out.println(a.compareTo(b));
      System.out.println(OffsetDateTime.INSTANT_COMPARATOR.compare(a, b));
      ========

      Output:
      ========
      -1
      1
      ========

      It does not makes sense. The correct value should be a<b.

      And it looks the implementation of INSTANT_COMPARATOR is incorrect:
      =========
      public static final Comparator<OffsetDateTime> INSTANT_COMPARATOR = new Comparator<OffsetDateTime>() {
          @Override
          public int compare(OffsetDateTime datetime1, OffsetDateTime datetime2) {
              int cmp = Long.compare(datetime1.toEpochSecond(), datetime2.toEpochSecond());
              if (cmp == 0) {
                  cmp = Long.compare(datetime1.toLocalTime().toNanoOfDay(), datetime2.toLocalTime().toNanoOfDay());
              }
              return cmp;
          }
      };
      =========

      I think we can not compare localTime part of OffsetDateTime directly. It should be convert to Instant firstly. Then compare epochSecond and nanoOfSecond.....

            rriggs Roger Riggs
            pzhang Patrick Zhang (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: