For the following snippet
GregorianCalendar a = new GregorianCalendar(2009, 11, 10);
System.out.println(a.getTime()); // Thu Dec 10 00:00:00 ICT 2009
a.add(Calendar.MONTH, 1);
System.out.println(a.getTime()); // Sun Jan 10 00:00:00 ICT 2010
When I change this line
a.add(Calendar.MONTH, 1);
into this line
a.set(Calendar.MONTH, a.get(Calendar.MONTH) + 1);
It returns the same result
// Sun Jan 10 00:00:00 ICT 2010
If it is December 2009, I thought set it to month + 1 (i.e January), the month should now be Januray 2009. But it is January 2010 instead.
So, what is the difference between set and add in this case?
Seems like set
is actually incrementing the year when the month is one more than December:
In the following
a.set(Calendar.MONTH, a.get(Calendar.MONTH) + 1);
a.get(Calendar.MONTH)
is December and when you add 1 on that, and set the result to the calendar object, it logically actually is the January of the next year, so it's fair enough to change the value of year also in this case.
Otherwise, the calendar instance would be in an illegal state, with an invalid value for month.
You can see for the following code:
Calendar cal = new GregorianCalendar(2009, Calendar.DECEMBER, 10);
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, Calendar.DECEMBER + 1);
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, Calendar.JANUARY + 5);
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, Calendar.DECEMBER + 13);
System.out.println(cal.getTime());
cal.set(Calendar.MONTH, -3);
System.out.println(cal.getTime());
The output is:
Thu Dec 10 00:00:00 CST 2009 Sun Jan 10 00:00:00 CST 2010 Thu Jun 10 00:00:00 CDT 2010 Tue Jan 10 00:00:00 CST 2012 Mon Oct 10 00:00:00 CDT 2011
So, if the value of month being set is out of range then the value of year is changed.