1

guys,i am confused by invoking the following method:Calendar.getInstance().get(Calendar.WEEK_OF_YEAR),the result got from that method is not right.Here is my Code:

    Locale.setDefault(Locale.CHINA);
    Calendar calendar = Calendar.getInstance();
    //we think Monday is the first day of a week in China,but not Sunday.
    calendar.setFirstDayOfWeek(Calendar.MONDAY);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = "2010-01-01";
    calendar.setTime(sdf.parse(dateString));
    System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));
    dateString = "2010-12-27";
    calendar.setTime(sdf.parse(dateString));
    System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));

The result is

DateString: 2010-01-01, week: 1//This may be wrong?
DateString: 2010-12-27, week: 1//This result is definitely wrong.

So here is the question, how to get the right week of year number using Calendar instance?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
George
  • 4,029
  • 2
  • 22
  • 26

2 Answers2

1

The locale has only influence on formatting (i.e., parsing and formatting the date as Chinese). You need to set the timezone to China. Fix the Calendar#getInstance() line as follows:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CST")); // China Standard Time
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • To @BalusC, CST is short for Central Standard Time, China Standard Time or Cuba Standard Time. In order to use China Standard Time(CST),we need the locale infomation too. – George Jan 05 '11 at 03:38
  • It is recommended to use the long timezone names. In this case "Asia/Shanghai" – eckes Jan 06 '12 at 20:24
1

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(4);
joutos
  • 11
  • 1