SimpleDateFormat gives java.lang.classcastexception: java.util.date

三世轮回 提交于 2019-12-11 11:32:13

问题


String str = "13/06/2011";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date)formatter.parse(str);

回答1:


I guess that your Date class is actually a java.sql.Date.




回答2:


What does your import statement say? Are you importing some other class (for example java.sql.Date) by accident? What does the compiler say when you remove the class cast (which should not be there)?




回答3:


DateFormat.parse() returns an instance of java.util.Date and not java.sql.Date. In order to convert from java.util.Date to java.sql.Date, I do the following:

java.util.Date fromDate = df.parse(fromdate1);  
java.sql.Date sqlDate = new java.sql.Date(fromDate.getTime()); 



回答4:


It simply means you are assigning java.util.Date in java.sql.Date

From your example you have to do following :

String str = "13/06/2011";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = (java.util.Date)formatter.parse( str );


来源:https://stackoverflow.com/questions/6327392/simpledateformat-gives-java-lang-classcastexception-java-util-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!