3

我在我的应用程序中使用自定义日历。我已经给用户选项来选择一周的第一天,这可能是:Saturday, Sunday, Monday

我想获取一个月中的周数 - 取决于一周开始的时间,覆盖周开始的默认值 - Sunday

代码:

public int getWeeksOfMonth(int year, int month) { 
    Calendar calendar = Calendar.getInstance(); 
    calendar.set(Calendar.MONTH, month-1);
    calendar.set(Calendar.YEAR, year);
    int numOfWeeksInMonth = calendar.getActualMaximum(Calendar.WEEK_OF_MONTH); 

    return numOfWeeksInMonth;
}
4

3 回答 3

3

尝试先设置一周的第一天:

Calendar.setFirstDayOfWeek()

于 2012-10-01T15:26:07.800 回答
2

尝试

calendar.setFirstDayOfWeek(Calendar.MONDAY); //sets first day to monday, for example.

在您的情况下,您可能想要这样做:

public int getWeeksOfMonth(int year, int month, int weekStart) { 
    Calendar calendar = Calendar.getInstance();  
    calendar.set(Calendar.MONTH, month-1);
    calendar.set(Calendar.YEAR, year);
    calendar.setFirstDayOfWeek(weekStart);
    int numOfWeeksInMonth = calendar.getActualMaximum(Calendar.WEEK_OF_MONTH); 

    return numOfWeeksInMonth;
}

并使用一行调用该方法,例如

int weeks = getWeeksOfMonth(2012, 5, Calendar.WEDNESDAY);
于 2012-10-01T15:26:54.960 回答
0
于 2017-09-09T22:19:21.587 回答