天天看點

year 和 weak year 的差別

java 中使用 SimpleDateFormat 時,會遇到 year 和 week year 這兩個概念,特此記錄。

google 答案:

A week year is in sync with a WEEK_OF_YEAR cycle. All weeks between the first and last weeks (inclusive) have the same week year value. Therefore, the first and last days of a week year may have different calendar yearvalues.

Stackoverflow的一個具體問題及其解釋:

For example, January 1, 1998 is a Thursday. If getFirstDayOfWeek() is MONDAY and getMinimalDaysInFirstWeek() is 4 (ISO 8601 standard compatible setting), then week 1 of 1998 starts on December 29, 1997, and ends on January 4, 1998. The week year is 1998 for the last three days of calendar year 1997. 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 and their week year is 1997.

檢視源碼

​java8(jdk1.8.0_171) 中,SimpleDateFormat.java 檔案中的 subFormat 函數處理兩種 year 的代碼:

case PATTERN_WEEK_YEAR: // 'Y'
case PATTERN_YEAR:      // 'y'
    if (calendar instanceof GregorianCalendar) {
        if (count != 2) {
            zeroPaddingNumber(value, count, maxIntCount, buffer);
        } else {
            zeroPaddingNumber(value, 2, 2, buffer);
        } // clip 1996 to 96
    } else {
        if (current == null) {
            zeroPaddingNumber(value, style == Calendar.LONG ? 1 : count,
                              maxIntCount, buffer);
        }
    }
    break;
           

結論

以上源碼說明,year 和 week year 的處理方式一緻。至少在java8(jdk1.8.0_171)是這樣的。

『注:本文來自部落格園“小溪的部落格”,若非聲明均為原創内容,請勿用于商業用途,轉載請注明出處http://www.cnblogs.com/xiaoxi666/』