为什么Calendar类表现奇怪?

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

当我执行c.getTime()时,我得到了以下输出...

输出:

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会给我正确的日期和时间,如果有人能简单地解释一下,并且如果可能的话用一个简单明了的例子来说明,我将不胜感激。

是的,Calendar 中的月份从 开始,这有点奇怪。最好使用更高效的库 http://joda-time.sourceforge.net/。 - exexzian
如果您使用JDK 8,应该优先选择java.time包而不是JODA。它已经被整合到JDK中了。 - duffymo
3个回答

5

Calendar中的月份从0开始计数。

公历和儒略历中的第一个月是1月,表示为0。

假设使用公历,11表示十二月,12表示明年的1月,这正是您的程序所显示的方式。


2

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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接