Java calendar problem, JDK 1.6.0.22

后端 未结 2 1487
遇见更好的自我
遇见更好的自我 2021-02-10 16:01

I have a problem with getting the week of year. On my machine JDK 1.6.0.22 version is installed, on another machine 1.6.0.21. And both machines return different results:

相关标签:
2条回答
  • 2021-02-10 16:37

    Don't use the JDK date/time classes - use JODA Time instead.

    0 讨论(0)
  • 2021-02-10 16:43

    This excerpt from the API documentation explains why this difference can occur:

    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.

    And from the source code of Calendar:

    Both firstDayOfWeek and minimalDaysInFirstWeek are locale-dependent.

    So it's the locale that determines this, not the time zone! Apparently, in some locales, week 1 of a year is considered to begin in the previous year. Try running this:

        Calendar cal = new GregorianCalendar();
        System.out.println(Locale.getDefault());
        System.out.println(cal.getMinimalDaysInFirstWeek());
        System.out.println(cal.getFirstDayOfWeek());
    

    I bet that either you're running the different versions in different locales, or the locale data changed between these versions. The result "1" could even be the more correct one and due to a bug fix in the locale data.

    0 讨论(0)
提交回复
热议问题