Java calendar problem, JDK 1.6.0.22

2020-06-05 06:14发布

问题:

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:

(1.6.0.22) week is: 1
(1.6.0.21) week is: 52

For this code:

      try {
         Calendar current = new GregorianCalendar();
         DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
         Date d = df.parse("2010-12-28 19:04:38 GMT");
         current.setTime(d);
         int currentWeek = current.get(Calendar.WEEK_OF_YEAR);
         System.out.println("week is: "currentWeek);
      } catch (ParseException e) {
        e.printStackTrace();
      }

Why does JDK 1.6.0.22 give the wrong result?

回答1:

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.



回答2:

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