0

I am trying to fetching current month as int from calender but getting wrong month number.

I have used below code :

public static Date getTodayDate() {
    Calendar calendar = Calendar.getInstance();
    return calendar.getTime();
}

private static int getMonthFromDate() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(getTodayDate());
    return cal.get(Calendar.MONTH);
}

public static void main(String[] arps) {
    System.out.println("Current Month in Integer :: " + getMonthFromDate());
}

Output :- Current Month in Integer :: 5

Expected Output :- Current Month in Integer :: 6

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94

2 Answers2

2

The month in Calendar is zero-based, i.e. Jan = 0. The documentation gives the full details.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

The Months are numbered from 0 (January) to 11 (December).

Use: System.out.println("Current Month in Integer :: " + getMonthFromDate()+1);

haMzox
  • 2,073
  • 1
  • 12
  • 25