问题描述
我试图了解 java.util.Calendar.get(java.util.Calendar.WEEK_OF_YEAR)
的工作原理,但似乎我遗漏了一些要点.
I'm trying to understand how java.util.Calendar.get(java.util.Calendar.WEEK_OF_YEAR)
works, but it seems that I'm missing some points.
String time = "1998-12-31"; // year month day
java.util.Calendar date = java.util.Calendar.getInstance();
date.setTime((new java.text.SimpleDateFormat("yyyy-MM-dd")).parse(time));
System.err.println("Week of year = " + date.get(java.util.Calendar.WEEK_OF_YEAR));
// Week of year = 1 Why ???
为什么 date.get(java.util.Calendar.WEEK_OF_YEAR)
在一年的最后一周返回 1?
Why date.get(java.util.Calendar.WEEK_OF_YEAR)
returns 1 for the last week of the year?
此外,"1998-01-01"
的 WEEK_OF_YEAR
为 1,"1998-12-23"
为 52.
有人对此行为有解释吗?
Moreover, WEEK_OF_YEAR
for "1998-01-01"
is 1 and for "1998-12-23"
it is 52.
Does anybody have an explanation for this behavior?
推荐答案
来自 java.util.Calendar javadoc:
日历使用两个参数:一周的第一天和 first 中的最少天数周(从 1 到 7).这些数字取自语言环境资源构建日历时的数据.它们也可以被指定明确地通过设置它们的值的方法.
First Week
Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for setting their values.
在设置或获取 WEEK_OF_MONTH 或 WEEK_OF_YEAR 字段时,日历必须将月份或年份的第一周确定为参照点.一个月或一年的第一周被定义为从 getFirstDayOfWeek() 和至少包含该月的 getMinimalDaysInFirstWeek() 天或年.周数 ..., -1, 0 在第一周之前;周数2, 3,... 跟着它.请注意,归一化编号返回get() 可能不同.例如,一个特定的 Calendar 子类可能将一年中第 1 周的前一周指定为前一周的第 n 周年.
When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.
所以它是特定于语言环境的.在您的情况下,如果该周包含新年后的几天,则将其计为新年的第 1 周.
So it's locale-specific. In your case, if the week contains days from new year, it is counted as week 1 from the new year.
您可以使用 更改此行为日历#setMinimalDaysInFirstWeek(int).
这篇关于了解 java.util.Calendar WEEK_OF_YEAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!