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

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

8 Comments

If I remove the cast, it gives me compilation error. Type mismatch: cannot convert from java.util.Date to java.sql.Date
@vijay you should import java.util.Date instead of java.sql.Date.
Thanks Howard. I did that and now I am not getting the cast exception. But now I am getting the below exception. Java.text.ParseException: Unparseable date: 12/21/2011
@vijay Do you now have another format (other than posted in your question)? It looks like because with above format it should work (nevertheless you seem to have MM/dd/yyyy now instead of dd/MM/yyyy).
This is my exact code .....SimpleDateFormat dateFormat = new SimpleDateFormat("MM:dd:yyyy"); Date convertedDate; try { convertedDate = dateFormat.parse(dob); dateFormat.parseObject(dob); } catch (ParseException e) { e.printStackTrace(); } and DOB is in this format : 12/21/2011
|
2

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

2 Comments

If I remove the cast, it gives me compilation error. Type mismatch: cannot convert from java.util.Date to java.sql.Date
And there is your answer. Wrong import statement.
2

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

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

1 Comment

After about an hour of looking, I found this and it works great.

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.