Reputation: 253
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 . 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);
Upvotes: 1
Views: 2102
Reputation: 15553
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.
}
Upvotes: 1
Reputation: 45070
You cannot simply cast a String
to a Date
. To get a Date
from a String
object which has the String
representation of Date
, use SimpleDateFormat.
E.g:
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);
Upvotes: 1
Reputation: 12754
You can use:
return new SwitchInputType<Date>(new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(memberValue));
Upvotes: 1
Reputation: 475
You should first convert the string to date object before assigning to a Date. Use SimpleDateFormat.parse() method to parse the string to a Date object.
Upvotes: 1
Reputation: 6516
Try to create new date object like this Date date = new Date(long)
or if you created this string using Date class use its static method Date.valueOf(String s)
.
Upvotes: 1
Reputation: 4202
If its a string, you need to parse it. Try using SimpleDateFormat with appropriate format.
Upvotes: 1
Reputation: 6075
SimpleDateFormat parserSDF=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = parserSDF.parse(memberValue);
Upvotes: 1