YoungMaster
YoungMaster

Reputation: 405

ClassCastException when converting String to Date in Java

I'm getting the error

java.lang.ClassCastException: java.util.Date
at avb.Test.main(Test.java:38)
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")

from the code

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String tmp = "2012-03-16 18:58:14.0";
Date MaxCmTimerUpdate = (Date)df.parse(tmp);

What am I doing wrong? How do I fix it?

Upvotes: 0

Views: 522

Answers (3)

Tom
Tom

Reputation: 4180

does this work:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String tmp = "2012-03-16 18:58:14.0";
java.util.Date maxCmTimerUpdate = df.parse(tmp);

if so, the other 2 answers are right.

Upvotes: 1

dty
dty

Reputation: 18998

Are you accidentally importing java.sql.Date instead of java.util.Date? It's the only reason you would need that cast in there at all.

Damn! Beaten by Jon Skeet AGAIN! Jon, what DO Google pay you for? ;-)

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500953

My guess is that you've got an import for java.sql.Date (or some other Date type), whereas SimpleDateFormat parses to a java.util.Date. You shouldn't need the cast at all.

You won't be able to cast to a different Date type - if you need to create a java.sql.Date, you'll have to create a new one based on the java.util.Date, e.g.

Date timerUpdate = new Date(df.parse(tmp).getTime());

Upvotes: 5

Related Questions