简体   繁体   中英

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.

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.

public final static int WEEK_OF_YEAR = 3; is inside source of Calendar.

When you access WEEK_OF_YEAR it prints value of this field, it would be treated like accessing static field of Calendar class.

If you want get week, you need to do Integer week = cal.get(Calendar.WEEK_OF_YEAR);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM