2012-08-26 32 views
3
Calendar c = Calendar.getInstance(); 
c.set(2019, 12, 29); 

当我做c.getTime()我得到了下面的输出...为什么Calendar类的这种怪异行为

输出:

Wed Jan 29 17:15:27 IST 2020 //本来应该是2019

/////------------------------------------------------- ------------ //////

Calendar c = Calendar.getInstance(); 
c.set(2019, 11, 29); 

,当我做c.getTime()我得到了下面的输出...

输出:

Sun Dec 29 17:18:23 IST 2019

现在我不知道为什么从第12位改变月份至11日给了我正确的日期和时间,如果有人能够简单地解释这一点,并且如果可能的话用一个简单的小例子,我会非常感激。

+0

是的'日历'的月份从零开始,这有点奇怪。最好使用更高效的库http://joda-time.sourceforge.net/ – exexzian

+0

如果你使用JDK 8,你应该更喜欢java.time包到JODA。它已被折叠到JDK中。 – duffymo

回答

5

月在Calendar是从零开始

年在格里高利历和罗马儒略历的第一个月是一月份是0

假设公历日历,11是12月,而12是明年1月,正如您的程序显示它的方式。

+0

+1简单直接的解释..... –

+0

我接受你的回答.......感谢你的快速和良好的回应 –

1
public final void set(int year, 
         int month, 
         int date) 
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are retained. If this is not desired, call clear() first. 
Parameters: 
year - the value used to set the YEAR calendar field. 
month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January. 
date - the value used to set the DAY_OF_MONTH calendar field. 

所以月份范围0-11。当你使用12时,它会进入明年。

参考:HTTP://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#set(INT,INT,INT)