java.util.date cannot be cast to java.sql.date

java

If you get a “java.util.Date cannot be cast to java.sql.Date” error, it means that you are trying to cast an object of type java.util.Date to an object of type java.sql.Date, but these two types are not compatible.

The java.util.Date class represents a date and time, while the java.sql.Date class represents a date (year, month, and day) in the calendar.

To fix the error, you need to convert the java.util.Date object to a java.sql.Date object. You can do this by using the valueOf() method of the java.sql.Date class, which takes a java.util.Date object as an argument and returns a java.sql.Date object:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

Alternatively, you can use the toInstant() method of the java.util.Date class to convert the date to an Instant object, and then use the toLocalDate() method to convert the Instant object to a LocalDate object. You can then use the toSqlDate() method to convert the LocalDate object to a java.sql.Date object:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = java.sql.Date.valueOf(utilDate.toInstant().toLocalDate());