Calendar class confusion

耗尽温柔 提交于 2021-01-29 02:27:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!