13

Possible Duplicate:
How to convert java.util.date to java.sql.date?

I found error on my function, it shows error result after initializing the newInstance() method from DatatypeFactory df , I'm getting another error:

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

I just change the package name from

java.util.Date into java.SQL.Date

then casting:

Date dateStarting  = (Date) jDateChooserStart.getDate();
Date dateEnding    = (Date) jDateChooserEnd.getDate();

How to resolve this issue?

(post before: Convert jcalendar Date into XMLGregorianCalendar Getting Null Value)

Community
  • 1
  • 1
randytan
  • 1,029
  • 5
  • 23
  • 52

2 Answers2

32

It's not possible to cast from java.util.Date to java.sql.Date. You need to convert from one type to the other instead:

java.util.Date utilStartDate = jDateChooserStart.getDate();
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());
João Silva
  • 89,303
  • 29
  • 152
  • 158
4

From the class cast exception you can see that these are 2 distinct types and can't be cast the from one to the other. To convert from java.util.Date to java.sql.Date, you can use:

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
Reimeus
  • 158,255
  • 15
  • 216
  • 276