gpt4 book ai didi

Java:GregorianCalendar 返回错误的数据

转载 作者:行者123 更新时间:2023-11-29 06:10:11 25 4
gpt4 key购买 nike

我想计算一年中特定周数的星期一。我是这样做的:

final GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY);
calendar.clear();
calendar.set(Calendar.YEAR, 2012); // set to 2012
calendar.set(Calendar.WEEK_OF_YEAR, 20); // set to week number 20
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); // set time zone

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy"); // german format
System.out.println(sdf.format(calendar.getTime())); // return date

这必须返回 2012 年 5 月 14 日(德语格式的 14.05.12),但它返回 2012 年 5 月 16 日,但这是错误的。

因此,对于 2012 年,它的 +2、2011 年是正确的,而 2010 年是 -1。

为什么 GregorianCalendar 计算错误的日期?

提前致谢,来自德国的问候。

最佳答案

这将取决于 getFirstDayOfWeek() 返回的内容以及 1 月 1 日是哪一天。

来自 Javadocs:

Values calculated for the WEEK_OF_YEAR field range from 1 to 53. Week 1 for a year is the earliest seven day period starting on getFirstDayOfWeek() that contains at least getMinimalDaysInFirstWeek() days from that year. It thus depends on the values of getMinimalDaysInFirstWeek(), getFirstDayOfWeek(), and the day of the week of January 1. Weeks between week 1 of one year and week 1 of the following year are numbered sequentially from 2 to 52 or 53 (as needed).

For example, January 1, 1998 was a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (these are the values reflecting ISO 8601 and many national standards), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. If, however, getFirstDayOfWeek() is SUNDAY, then week 1 of 1998 starts on January 4, 1998, and ends on January 10, 1998; the first three days of 1998 then are part of week 53 of 1997.

关于Java:GregorianCalendar 返回错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7189744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com