UnsupportedOperationException - Why can't you call toInstant() on a java.sql.Date?
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();
Check 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.
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());
// OR
new java.util.Date(sqlDate.getTime()).toInstant();
Will return the same result because toInstant() call Instant.ofEpochMilli(getTime()) internally.
public Instant toInstant() {
return Instant.ofEpochMilli(getTime());
}