开发者

How to get the right week of year number through a Calendar?

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.Her开发者_Go百科e 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?


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


Try this:

Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(4);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜