1

I am trying to parse a formatted date back to a Date object but I keep encountering exceptions, here is my code:

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);
date = dateFormat.parse(dateString);

When I try a date like Apr 17, 2016 it gives me an ParserException to say Unparseable date: "Apr 17, 2016" (at offset 12)

2
  • can u try with just 3 Ms. SimpleDateFormat("MMM d, yyyy ", Locale.ENGLISH) Commented Apr 19, 2016 at 17:20
  • 2
    "MMMM" means "full month name" which would mean "April" rather than "Apr". You want "MMM" meaning "abbreviated month name". Always check your format against the documentation when you run against problems like this. Also note that you have a trailing space in your pattern, which you appear not to have in your actual text. Commented Apr 19, 2016 at 17:20

4 Answers 4

2

When you provide a date format string, all of the characters must account for all of the text in the dateString somehow, including the literal space characters.

You have a space character at the end of your format string:

"MMMM d, yyyy "

Eliminate that space (or include a space at the end of your dateString string).

The format strings MMMM or MMM will parse Apr just fine.

Text: For formatting, if the number of pattern letters is 4 or more, the full form is used; otherwise a short or abbreviated form is used if available. For parsing, both forms are accepted, independent of the number of pattern letters.

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

Comments

2

You have a little bundler in your date mask: The last blank is too many:

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);

It should be:

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);

That's why the error points to "offset 12": The DateFormat expects a blank at that position.

Comments

1

You need to remove the last blank space on the string format.

You actually have

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);

And it should be

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);

Comments

0

Try as follows

DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);

Date date = dateFormat.parse(dateString);

2 Comments

Add Date before date
the space was the cause of my misfortune.

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.