0

I need to format my date (in Java) which is in String format. When I use the following code, taken from an tutorial/reference source, it just gives the following error. I have tried everything I can think of.

My code:

SimpleDateFormat format = new SimpleDateFormat ("E dd/MMM/yy");
java.util.Date date = format.parse ("12/31/2006");
System.out.println (date);

This results in the following error:

java.text.ParseException: Unparseable date: "12/31/2006"

I am actually trying to format this string "2011-7-27" but it gave the same error, which resulted me in trying that format for the string I feed to it.

Is there anything you can see which I mess up somewhere?

1 Answer 1

3

The code you've given isn't taken from the page you linked to. That format string doesn't appear anywhere on the page.

You've included an "E" in the format specifier, which corresponds to the day of the week - but then you're not providing that. You've also used "MMM" as the month specifier, which would be a textual representation (e.g. "Jul"). Finally, you've specified "yy" for the year, but then given 4 digits. (This won't actually cause an issue - it'll cope with four digits - but it's better to specify the format you actually expect.) If you just want to give "12/31/2006" your format should be "MM/dd/yyyy".

If you actually want to parse "2011-7-27" you should use "yyyy-M-dd" as the format string.

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

9 Comments

and MMM I believe means a 3 letter month abreviation like Jan, Feb etc. but you give 2 digits!!! Also your example date has month and day in the wrong order ... look long and carefully at your format string and you see it wants 2 digits for a DAY, 3 letters for a Month and 2 digits for a year, your date "12/31/2006" is completely bollocks.
@Angel: Yup, I covered that :)
Sorry, your more elaborated answer was not theren when I formulated mine ;D
@Angel: We need a "this post has been edited" even when one is writing a comment, it seems :)
Note: the number of characters is only important for formatting and only the month ones for parsing... M/d/y and y-M-d are as good as MM/dd/yyyy and yyyy-MM-dd for parsing. Month work differently since with 3 or more M the month is interpreted as text.
|

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.