error casting Java.Util.Date into Java.Sql.Date [d

2019-02-06 11:16发布

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)

2条回答
Bombasti
2楼-- · 2019-02-06 11:53

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());
查看更多
够拽才男人
3楼-- · 2019-02-06 12:09

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()); 
查看更多
登录 后发表回答