Search code examples
java

Error getting month while using Calendar object


I'm using Calendar API to manipulate date. Here is snippet of code i'm trying.

Date date=new SimpleDateFormat("dd/mm/yyyy").parse("05/10/2013");
              Calendar cal=Calendar.getInstance();
              cal.setTime(date);
              int month=cal.get(Calendar.MONTH);

Here i should get month as 9(Oct) but its returning 0(Jan).Even if I change date it still returns 0(Jan). Why this is happening? Please help me.


Solution

  • use MM instead of mm small m gives Minute in hour and to get Month use capital M

    Date date=new SimpleDateFormat("dd/MM/yyyy").parse("05/10/2013");
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    int month=cal.get(Calendar.MONTH);
    System.out.println("" + month);
    

    Output:

    9
    

    Java Docs

    enter image description here