0

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?

1
  • 1
    Are you sure you're casting to java.util.Date in the line (Date) df.parse(tmp)? Besides, DateFormat.parse(String) already returns a java.util.Date, so there's no need for the casting. Commented Mar 16, 2012 at 19:23

3 Answers 3

5

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.