5

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;

}
5
  • 2
    What's your default Locale? Try with SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy", Locale.US);
    – Alexis C.
    Commented Nov 29, 2014 at 15:52
  • @SotiriosDelimanolis my date string does not have dashes
    – Asalas77
    Commented Nov 29, 2014 at 15:57
  • @ZouZou my locale is Poland
    – Asalas77
    Commented Nov 29, 2014 at 15:57
  • Read your exception carefully.
    – SSC
    Commented Nov 29, 2014 at 16:00
  • @SotiriosDelimanolis ok i fixed a typo. I am for sure giving "18 Dec 2015" as input and i get java.text.ParseException: Unparseable date: "18 Dec 2015" exception
    – Asalas77
    Commented Nov 29, 2014 at 16:03

2 Answers 2

7

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

1
  • 2
    Locale.US seems to have fixed it
    – Asalas77
    Commented Nov 29, 2014 at 16:04
1

You are passing input as "18-Dec-2015" instead of the form "dd MMM yyyy". Try and pass input like 18 Dec 2015 and it should work.

Not the answer you're looking for? Browse other questions tagged or ask your own question.