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

java.util.Date to Instant conversion not consistent

XMLWordPrintable

    • generic
    • generic

      FULL PRODUCT VERSION :
      java version "1.8.0_144"
      Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
      Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Windows 10 64 bit

      A DESCRIPTION OF THE PROBLEM :
      The methods Date#toInstant() and Date#from(Instant) do only work as long as Date#getTime returns a positive long.
      java.time.Instant should treat the output of Date#getTime unsigned long just like java.util.Date treats it.
      I don't mind the inconsistencies, that the Date constructor treats the longs as unsigned while the static method of Instant treats them as signed, the bug is that the conversion returns the false Instant/an ArithmeticException

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run Date.from(Instant.now().plusMillis(Long.MAX_VALUE));
      Get an ArithmeticException although this Instant could be represented by a Date object

      Print new Date(Long.MIN_VALUE) and Instant.ofEpochMilli(Long.MIN_VALUE) to the console. They do not represent the same point in time although they should

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Date.from(Instant) should return a date object as long as a Date object can represent the given Instant
      ACTUAL -
      Instant#getEpochMillis throws an ArithmeticException, because the resulting long cannot be returned as signed integer

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      Exception in thread "main" java.lang.IllegalArgumentException: java.lang.ArithmeticException: long overflow
      at java.util.Date.from(Date.java:1359)
      at HelloWorld.main(HelloWorld.java:10)
      Caused by: java.lang.ArithmeticException: long overflow
      at java.lang.Math.multiplyExact(Math.java:892)
      at java.time.Instant.toEpochMilli(Instant.java:1237)
      at java.util.Date.from(Date.java:1357)
      ... 1 more

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.Date;
      import java.time.Instant;

      public class HelloWorld {
        public static void main(String[] args) {
          System.out.println(Date.from(Instant.now().plusMillis(Long.MAX_VALUE))); // ArithmeticException although this Instant can be represented by java.util.Date
        }
      }
      ---------- END SOURCE ----------

            naoto Naoto Sato
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: