为什么 Java Calendar set(intyear,intmonth,intdate) 不返回正确的日期?

发布于 2024-10-16 16:29:20 字数 719 浏览 1 评论 0原文

根据文档,日历 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 日???

According to doc, calendar set() is:

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.

code:

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

System.out.println(sDate);

output:

Wed Mar 01 19:32:21 JST 2000

Why it's not Jan 30 ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

稳稳的幸福 2024-10-23 16:29:20

1 表示月份是二月。 2月30日改为3月1日。
您应该将月份设置为 0。最好是使用 Calendar 中定义的常量:

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

1 for month is February. The 30th of February is changed to 1st of March.
You should set 0 for month. The best is to use the constant defined in Calendar:

c1.set(2000, Calendar.JANUARY, 30);
明媚殇 2024-10-23 16:29:20

Calendar 对象中的月份从 0 开始

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

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
猫九 2024-10-23 16:29:20

示例中选择的日期很有趣。示例代码块为:

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

当我第一次阅读这个例子时,我认为输出是错误的,但它是正确的:)

  • Calendar.Month 从 0 开始,所以 1 表示二月。
  • 2 月最后一天是 28,因此输出应该是 3 月 2 日。
  • 但选择的年份很重要,它是 2000 年,这意味着 2 月 29 日,所以结果应该是 3 月 1 日。

Selected date at the example is interesting. Example code block is:

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

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文