How to parse ‘dd MMM yyyy’

How to convert date fromat from “dd MMM yyyy” to “yyyy-MM-dd”?

I know I have to use SimpleDatFormat but it doesn’t work, neither does any solution from similar questions.

I have a date “18 Dec 2015” that I am trying to format but I get this

java.text.ParseException: Unparseable date: "18 Dec 2015"

Here’s my code:

public String parseDate(String d) {
    String result = null;
    Date dateObject = null;
    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");
    try {
        dateObject = dateFormatter.parse(d);
        dateFormatter.applyPattern("yyyy-MM-dd");
        result = dateFormatter.format(dateObject);

    } catch (ParseException e) {
        System.out.println(e);
    }

    return result;

}

Answer

Did you try

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");

instead of

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy");

(note the hyphens, since your pattern doesn’t match your input)

Also helpful: using Locale.US as recommended by @ZouZou

Leave a Reply

Your email address will not be published. Required fields are marked *