78

The java.util.Date class has a method called toInstant() that converts the Date instance to a java.time.Instant.

The java.sql.Date class extends the java.util.Date class, but when I attempt to call toInstant() on a java.sql.Date, I receive an UnsupportedOperationException.

Why is toInstant() an unsupported operation on java.sql.Date?

And what is the "correct" way to convert a java.sql.Date to a java.time.Instant?

Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102

6 Answers6

58

The correct mapping between java.sql.Date and java.time is LocalDate:

LocalDate date = sqlDate.toLocalDate();

If you really must, you can then derive an Instant, although the extra information (time) will be arbitrary. For example:

Instant i = date.atStartOfDay(ZoneOffset.UTC).toInstant();
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Wish I could accept two answers... This answers the second part of my question perfectly, but the main question was why you can't call `toInstant()` on a `java.sql.Date`, so I had to accept [@YassinHajaj](http://stackoverflow.com/users/5050667/yassin-hajaj)'s [answer](http://stackoverflow.com/a/36435570/2561365). This answer needs more upvotes. – Andrew Mairose Apr 06 '16 at 13:26
  • Since `date` is a LocalDate (local timezone), shouldn't the conversion to Instant (which is UTC) specify the local timezone?: `Instant i = date.atStartOfDay(ZoneId.systemDefault()).toInstant()` – Curtis Yallop Oct 29 '21 at 16:38
  • LocalDate date = sqlDate.toLocalDate(); is not performable – Yannick Mussche Dec 01 '22 at 16:29
  • @YannickMussche not sure what you mean: https://docs.oracle.com/en/java/javase/17/docs/api/java.sql/java/sql/Date.html#toLocalDate() – assylias Dec 03 '22 at 21:30
  • try it in your IDE, it doesn't work. – Yannick Mussche Dec 04 '22 at 16:15
  • @YannickMussche https://ideone.com/4G8O06 – assylias Dec 05 '22 at 12:20
41

According to the JavaDoc

Since sql.Date does not have a time component, there is no possibility to convert it to time.Instant

This method always throws an UnsupportedOperationException and should not be used because SQL Date values do not have a time component.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 5
    Now, the question is _why_ it was designed this way. One could imagine it defaults with time info set to 0. Can't find anything in the mailing list. – Tunaki Apr 05 '16 at 19:58
  • 3
    @Tunaki The logic makes me think it is because the parent class `util.Date` has a public `toInstant` method that should not be used by the child class. So instead of making it `final` (to keep the Inheritance logic), they preferred the option of overriding it and making it unusable. – Yassin Hajaj Apr 05 '16 at 20:02
  • @Tunaki probably because, as you point out, any conversion into an Instant would require setting some data arbitrarily (time, time zone). – assylias Apr 06 '16 at 07:24
  • 1
    But `Instant` using the same logic that `java.util.Date` uses would produce correct and logical results, while avoiding violating the polymorphism contract. Oracle has made a very headscratching choice, there. – Haroldo_OK Jun 24 '22 at 12:15
37

java.sql.Date supports only Date components (date, month, year). It does NOT support time components (hour, minute, second, millisecond). toInstant requires both Date and Time components, so toInstant on java.sql.Date instance throws UnsupportedOperationException exception.

toInstant Java doc

This method always throws an UnsupportedOperationException and should not be used because SQL Date values do not have a time component.

java.util.Date OR java.sql.Timestamp has both Date/Time components, so toInstant() works!

You can do like this:

// Time is 00:00:00.000

new java.util.Date(sqlDate.getTime()).toInstant() 

Updated:

Instant.ofEpochMilli(sqlDate.getTime());

// and
new java.util.Date(sqlDate.getTime()).toInstant();

will return the same result because the toInstant() method calls Instant.ofEpochMilli(getTime()) internally.

public Instant toInstant() {
    return Instant.ofEpochMilli(getTime());
}
LHA
  • 9,398
  • 8
  • 46
  • 85
  • Which is more "correct"? `Instant.ofEpochMilli(sqlDate.getTime());` or `new java.util.Date(sqlDate.getTime()).toInstant();` – Andrew Mairose Apr 05 '16 at 19:44
  • You can’t convert a java.sql.Date into an Instant without supplying a timezone. Calling getTime() at an java.sql.Date is meaningless. As pointed out in other comments, java.sql.Date is only a LocalDate and doesn’t represent an instant in time. – Alexander Kiel Nov 29 '17 at 08:19
  • I didn't call toInstant on java sql date. I did call toInstant on java util date and it is ok for the case. – LHA Nov 29 '17 at 15:02
19

The answers given so far until now concentrate on the detail that java.sql.Date has no time information. That is correct but not the real or sufficient reason why this type cannot offer a direct conversion to Instant. Unfortunatly the documentation of Java-8 does make the same mistake to let users think the problem is just because of missing time information.

Conceptually, the type java.sql.Date represents a local type. It models a calendar date which can be different in any region of our globe. But an Instant is the same on our globe around. So users need a timezone or a timezone offset to do the conversion.

Tragically, the type java.sql.Date inherits from java.util.Date which is a global type (instant-like). However, this inheritance really denotes implementation inheritance, and not type inheritance. One more reason to consider the design of these old JDBC-classes to be broken. Therefore it is indeed possible to use the hack to wrap the java.sql.Date via its method getTime() inside an instance of java.util.Date which finally allows direct conversion to an instant. But: This conversion implicitly uses the default timezone of the system.

So how to correctly convert in a pedantic way? Let's consider the documentation of Java-8 again which here points into the right direction:

java.sql.Date sqlDate = ...;
LocalDate calendarDate = sqlDate.toLocalDate();
ZonedDateTime zdt = calendarDate.atStartOfDay(ZoneId.of("Europe/Paris"));
Instant instant = zdt.toInstant();
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
6

If you don't have time in your Date - convert it to millis:

Instant.ofEpochMilli(date.getTime())
   .atZone(ZoneId.systemDefault())
   .toLocalDate();
Zon
  • 18,610
  • 7
  • 91
  • 99
1

The implementation of java.sql.Date (imho) is really not perfect.

In order to convert java.util.Date to LocalDate the web is full of code blocks like this:

dateToConvert.toInstant()
  .atZone(ZoneId.systemDefault())
  .toLocalDate();
  • above code works perfect for java.util.Date because of the way it implements toInstant(). (As expected " return Instant.ofEpochMilli(getTime())")
  • As java.sql.Date is a subclass of java.util.Date code operating on the Date object might now know it operates on a java.sql.Date. (Hey - that's one aspect of object orientation, right??). So if it gets java.util.Date code works well, if it gets java.sql.Date it fails.
  • Code could now explicitly check for the Date type, and then (if it operates on java.sql.Date) it could do a downcast to java.sql.Date and use the toLocalDate() method. Needless to say, that this is ugly.

As developer I'd like to have one method working properly - toLocalDate (internally using deprectated methods) only exists for java.sql.Date so cannot be used on java.util.Date, and toInstant fails on java.sql.Date.

I changed my "Date to LocalDate" conversion code to this:

public static LocalDate asLocalDate(java.util.Date date) {
    return date == null ? null : LocalDate.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault());
}

This works independent of the date type passed in. Basically it means "dont call java.util.Date.toInstant() as you might get a java.sql.Date, which then breaks your code.

I really don't understand why they implement such traps on purpose within the JDK.

  • It's a very head-scratching choice on the part of the original designers, indeed. There was no reason to break the polymorphic contract. – Haroldo_OK Jun 24 '22 at 12:18