java

incorrect week_of_year


Have next function to get week of year:

static public Integer getWeek(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setMinimalDaysInFirstWeek(1);
    cal.setTime(date);
    Integer week = cal.WEEK_OF_YEAR;
    Integer month = cal.MONTH;
    if ((week == 1) && (month == 12)) week = 52;
    return week;
}

Call the function with date=02.01.2013

What I see in debug:

  1. date = Wed Jan 02 00:00:00 SAMT 2013
  2. week = 3
  3. month = 2

I want to get: week=1, month=1. Right?

Where am I wrong?

JRE 1.6

Thanks a lot for advance.


Solution

  • Calendar.WEEK_OF_YEAR and Calendar.MONTH are static constants Calendar uses to look up fields. You want

    Integer week = cal.get(Calendar.WEEK_OF_YEAR);
    Integer month = cal.get(Calendar.MONTH);
    

    Also, note that (I think) January is considered month 0.