Search code examples
javadatesimpledateformat

Java date format conversion - getting wrong month


I have a problem in converting the date in Java. I don't know what I'm doing wrong.

String dateStr = "2011-12-15";
String fromFormat = "yyyy-mm-dd";
String toFormat = "dd MMMM yyyy";

try {
    DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
    Date date = (Date) fromFormatter.parse(dateStr);

    DateFormat toformatter = new SimpleDateFormat(toFormat);
    String result = toformatter.format(date);

} catch (ParseException e) {
    e.printStackTrace();
}

Input date is 2011-12-15 and I am expecting the result as "15 December 2011", but I get it as "15 January 2011"

What am I doing wrong?


Solution

  • Case-sensitive

    Your fromFormat uses minutes mm where it should use months MM.

    String fromFormat = "yyyy-MM-dd";