UnsupportedOperationException - Why can't you call toInstant() on a java.sql.Date?

Andrew Mairose picture Andrew Mairose · Apr 5, 2016 · Viewed 32.5k times · Source

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?

Answer

assylias picture assylias · Apr 6, 2016

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();