Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Calendar#add(int field, int amount) increments the calendar by a specified amount. In your case, it adds one month.

Calentar#set(int field, int value) sets a field to a specified value, leaving other fields unchanged. In your case, it sets the month to January.

Also see:

Calendar#roll(int field, int value) increments the specified field by the specified value but leaves the higher fields (in your case, year) unchanged (Oct 2010 + 4 months => Feb 2010)

If you have been set default value it will add value to current calender.(In your case)

If you want to set month value you can set it as below prior to set date.

Calendar cal = GregorianCalendar.getInstance(); cal.set(Calendar.MONTH, 0);

Will return month as January

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top