Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 225
Andrew Mairose Avatar asked Apr 05 '16 19:04

Andrew Mairose


People also ask

What is the difference between Java Util date and Java sql date?

sql. Date just represent DATE without time information while java. util. Date represents both Date and Time information.

What is Java sql date?

The java. sql. Date represents the date value in JDBC. The constructor of this class accepts a long value representing the desired date and creates respective Date object.


1 Answers

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(); 
like image 102
assylias Avatar answered Sep 19 '22 12:09

assylias