How to parse month full form string using DateFormat in Java?

tommy chheng picture tommy chheng · Feb 8, 2010 · Viewed 141.3k times · Source

I tried this:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy");
Date d = fmt.parse("June 27, 2007");

error:

Exception in thread "main" java.text.ParseException: Unparseable date: "June 27, 2007"

The java docs say I should use four characters to match the full form. I'm only able to use MMM successfully with abbreviated months like "Jun" but i need to match full form.

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.

https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Answer

Mark Byers picture Mark Byers · Feb 8, 2010

You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.

Try specifying the locale you wish to use, for example Locale.US:

DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27,  2007");

Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.