How to disassemble 'dd MMM yyyy'

How to convert date from "dd MMM yyyy" to "yyyy-MM-dd"?

I know what I need to use SimpleDatFormat

but it won't work, none of the solution from similar questions.

I have a date "Dec 18, 2015" which 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;

}

      

+3


source to share


2 answers


You tried

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

      

instead



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

      

(mark the hyphens as your pattern doesn't match your input)

Also helpful: using Locale.US

as recommended by @ZouZou

+2


source


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



0


source







All Articles