1

I have code in which I have to find the MONTH, so we have added months in that. The gettime() method is showing updated time but the MONTH field is not getting updated. In the below example the changed month is same as the current month.

Calendar cal = Calendar.getInstance();
System.out.println("Current time is "+ cal.getTime());
System.out.println("Current month is "+Calendar.MONTH);
cal.add(Calendar.MONTH, -2);

System.out.println("Changed time is "+ cal.getTime());
System.out.println("Changed month is "+Calendar.MONTH);

The output of above code is Current time is Mon Feb 22 17:59:13 IST 2016 Current month is 2 Changed time is Tue Dec 22 17:59:13 IST 2015 Changed month is 2

I don't want to use deprecated methods of calendar class to get months

JManish
  • 321
  • 4
  • 17

1 Answers1

4

Calendar.MONTH is a constant integer. What you want is rather:

int month = cal.get(Calendar.MONTH); // zero-based!!!
System.out.println("Month=" + (month + 1));
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126