[英]Cast string to Date error for return type -ClassCastException
I having method that i move type object (in this time type object is type String ) and i want to cast it to type date how should i do that . 我有一种方法可以移动类型对象(此时类型对象是String类型),并且我想将其强制转换为date类型,我该怎么做。 when i use the following code i getting error :
当我使用以下代码时,出现错误:
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
Code: 码:
} else if (typeName.equals("Date")) {
return new SwitchInputType<Date>((Date) memberValue);
SimpleDateFormat parserSDF=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = parserSDF.parse(memberValue);
You cannot simply cast a String
to a Date
. 您不能简单地将
String
转换为Date
。 To get a Date
from a String
object which has the String
representation of Date
, use SimpleDateFormat . 要从具有
Date
的String
表示形式的String
对象获取Date
,请使用SimpleDateFormat 。
Eg: 例如:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //Change format according to your needs.
Date date = new Date();
try{
date = sdf.parse((String)memberValue); //Update:- memberValue.toString() will also work.
}catch(ParseException pe){
//Do something on Exception.
}
return new SwitchInputType<Date>(date);
If its a string, you need to parse it. 如果是字符串,则需要对其进行解析。 Try using SimpleDateFormat with appropriate format.
尝试使用具有适当格式的SimpleDateFormat。
尝试创建像这样的新日期对象Date date = new Date(long)
或者如果您使用Date类创建了此字符串,请使用其静态方法Date.valueOf(String s)
。
You should first convert the string to date object before assigning to a Date. 您应该先将字符串转换为date对象,然后再分配给Date。 Use SimpleDateFormat.parse() method to parse the string to a Date object.
使用SimpleDateFormat.parse()方法将字符串解析为Date对象。
您可以使用:
return new SwitchInputType<Date>(new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(memberValue));
Something like this should work: 这样的事情应该起作用:
final SimpleDateFormat parsedDate = new SimpleDateFormat("yyyy-MM-dd");
final Date date;
try{
date = parsedDate.parse(stringValue);
} catch(Exception e) {
// handle the exception.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.