問題描述
我試圖了解 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!