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

toEpochMilli divides by one million instead of one thousand

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8u411
    • core-libs
    • generic
    • generic
    • Not verified

      ADDITIONAL SYSTEM INFORMATION :
       % java -version
      openjdk version "1.8.0_302"
      OpenJDK Runtime Environment (Temurin)(build 1.8.0_302-b08)
      OpenJDK 64-Bit Server VM (Temurin)(build 25.302-b08, mixed mode)

      A DESCRIPTION OF THE PROBLEM :
      The code below is wrong, at least in the else block. To add nanos to milliis the nanoseconds should be divided by 1000. Instead they're divided by 1000. That is, it converts the nanos to seconds instead of milliseconds.

          public long toEpochMilli() {
              if (seconds < 0 && nanos > 0) {
                  long millis = Math.multiplyExact(seconds+1, 1000);
                  long adjustment = nanos / 1000_000 - 1000;
                  return Math.addExact(millis, adjustment);
              } else {
                  long millis = Math.multiplyExact(seconds, 1000);
                  return Math.addExact(millis, nanos / 1000_000);
              }
          }

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Code like the following

              ZonedDateTime temporal = ZonedDateTime.of(2001, 8, 22, 3, 4, 5, 321000, UTC);
              Instant from = Instant.from(temporal);
              long epochMilli = from.toEpochMilli();

      The epochMilli value is incorrectly truncated to the second.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      321 milliseconds after the second
      ACTUAL -
      0 millisecond after the second

      CUSTOMER SUBMITTED WORKAROUND :
      Manually add in the miliseconds

      FREQUENCY : always


            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: