问题
I was playing with the Calendar class and got some confusing results:
Calendar thisCal = Calendar.getInstance();
thisCal.clear();
thisCal.set(2012,12,8);
System.out.println("Year is: " + thisCal.get(Calendar.YEAR));
System.out.println("Month is: " + thisCal.get(Calendar.MONTH));
System.out.println("Day of Month is: " + thisCal.get(Calendar.DAY_OF_MONTH));
The output:
Year is: 2013
Month is: 0
Day of Month is: 8
Confused I am!
回答1:
The MONTH
field is zero based (inherited from some POSIX API, I think). So you're setting it to the 13th month of 2012, which it interprets as the first month (with number 0) of 2013.
If you set the lenient
property to false
, it would throw an Exception instead.
回答2:
Month numbering starts from 0. More details here.
回答3:
Please read the API doc of Calendar.
Month starts at ZERO.
Therefore, if you set 12 as month, it is in fact the "13th month", which cause the "strange" result
来源:https://stackoverflow.com/questions/8807438/calendar-class-confusion