Chrometobia
Chrometobia

Reputation: 671

Parsing date string

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)

Upvotes: 1

Views: 341

Answers (4)

Federico Calvagna
Federico Calvagna

Reputation: 45

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

Upvotes: 1

Arshid KV
Arshid KV

Reputation: 10037

Try as follows

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

Date date = dateFormat.parse(dateString);

Upvotes: 0

Little Santi
Little Santi

Reputation: 8813

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.

Upvotes: 2

rgettman
rgettman

Reputation: 178323

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.

Upvotes: 2

Related Questions