SimpleDateFormat 给出 java.lang.classcastexception: java.util.date

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6327392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:24:16  来源:igfitidea点击:

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

javadatecastingsimpledateformat

提问by Vijay Nag

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

回答by Prince John Wesley

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

我猜你的Date班级实际上是一个java.sql.Date.

回答by ami ra

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

DateFormat.parse()返回java.util.Date和 not的实例java.sql.Date。为了从 转换java.util.Datejava.sql.Date,我执行以下操作:

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

回答by Thilo

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)?

你的进口声明说什么?您是否java.sql.Date意外导入了其他类(例如)?当您删除类强制转换(不应该在那里)时,编译器会说什么?

回答by Sumit Singh

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

它只是意味着你要分配 java.util.Datejava.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 );