-2

I have the following code snippet where i get continous error for casting java.util.date to java.sql.date.

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        storedProcedureCall.setLong(1, 12345);
        storedProcedureCall.setDate(2, (java.sql.Date) sdf.parse("09/02/2017"));
        storedProcedureCall.setDate(3, (java.sql.Date) sdf.parse("10/02/2017"));

What am i doing wrong here. I have imported the java.util.Date package as well.

Aby
  • 23
  • 6
  • Any reason why you are using the long outdated classes `java.util.Date` and `java.sql.Date`? I recommend [the modern Java date and time API known as JSR-310 or `java.time`](https://docs.oracle.com/javase/tutorial/datetime/). You can pass a `LocalDate` or other modern object to `PreparedStatement.setObject()`, also when using the `CallableStatement` subinterface, of course. – Ole V.V. Oct 23 '17 at 09:28
  • `java.sql.Date` extends (is a subclass of) `java.util.Date`. The `parse()` method returns a `java.util.Date`, and you can't cast it to a subclass: https://stackoverflow.com/questions/30414859/how-to-cast-subclass-object-to-superclass-object –  Oct 23 '17 at 10:35

1 Answers1

1

The class java.util.Date is totally different to java.sql.Date. Thus it can not be cast to.

You probably meant to use java.util.Date. Check your signature of storedProcedureCall#setDate, it probably accidentally imported java.sql.Date instead of java.util.Date.


Note that nowadays the Date class should not be used anymore. Instead use the new modern API located inside the package java.time. Like this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime dateTime = LocalDateTime.parse(dateAsString, formatter);
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • Incorrect, `java.util.Date` and `java.sql.Date` are *not* “totally different”. Unfortunately, just the opposite. `java.sql.Date` inherits from `java.util.Date`. So while `java.sql.Date` pretends to hold only a date without a time-of-day and without a time zone, it does indeed hold both a time-of-day and a time zone. Actually *two* time zones — while the date-time tracked as a count from UTC (and therefore represents a moment in UTC), there actually is a time zone assigned deep in the source code without any getter/setter. Total train wreck of bad design. Use *java.time* instead. – Basil Bourque Dec 31 '18 at 00:45