为什么Java日历集(int year,int month,int date)没有返回正确的日期?

2022-08-31 17:47:29

根据 doc,calendar set() 是:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#set%28int,%20int,%20int%29

set(int year, int month, int date) 
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.

法典:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

输出:

Wed Mar 01 19:32:21 JST 2000

为什么不是1月30日???


答案 1

1 月是 2 月。2月30日改为3月1日。应将月设置为 0。最好使用“日历”中定义的常量:

c1.set(2000, Calendar.JANUARY, 30);

答案 2

“日历”对象中的月份从 0 开始

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

推荐