Java date format conversion - getting wrong month

I have a problem in converting the date in java, don't know where i am going 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"

where am I going wrong?


Your fromFormat uses minutes where it should use months.

String fromFormat = "yyyy-MM-dd";

I think the fromFormat should be "yyyy-MM-dd".

Here is the format:

  • m == Minute in Hour
  • M == Month in Year

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


From format should be:

String fromFormat = "yyyy-MM-dd"

Look at the javadoc of SimpleDateFormat and look at what the m represents. Not months as you think but minutes.


 String fromFormat = "yyyy-MM-dd";