当月的星期一数?

时间:2014-07-18 11:23:55

标签: java

如何找到特定月份的星期一(例如4或5)的总数?

Calendar c = Calendar.getInstance();
int mon = c.getActualMaximum(Calendar.MONDAY);

这是正确的方法??

4 个答案:

答案 0 :(得分:0)

使用Calendar api,我能看到的最佳选择是:

  1. 获取实际的最大日期(即本月的天数)

  2. 将日历设置为该月的第一天并获取星期几

  3. 计算可以发生多少个星期一(即如果是28天,4月,如果29 4除非月份开始于星期一,如果30,4除非月份在星期一或星期二开始,如果31,4除非开始在星期一,星期二或星期三)。

答案 1 :(得分:0)

你可以使用这种方法

public int countMonday(int year, int month) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.MONDAY) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

更新

public int countDayOccurence(int year, int month,int dayToFindCount) {
    Calendar calendar = Calendar.getInstance();
    // Note that month is 0-based in calendar, bizarrely.
    calendar.set(year, month - 1, 1);
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    int count = 0;
    for (int day = 1; day <= daysInMonth; day++) {
        calendar.set(year, month - 1, day);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == dayToFindCount) {
            count++;
            // Or do whatever you need to with the result.
        }
    }
    return count;
}

然后您可以为每天的名称

调用此方法
   int countMonday = countDayOccurence(year,month,Calendar.MONDAY);
   int countTuesday = countDayOccurence(year,month,Calendar.TUESDAY);

...............................................

答案 2 :(得分:0)

至少在本月你需要的是:

    Calendar c = Calendar.getInstance();        
    int maxDaysInMonth = c.getMaximum(Calendar.DAY_OF_MONTH);
    int firstMonday = c.get(Calendar.MONDAY); // first monday in the month (Beware, 0 is the first day of the month)
    int mondays = 0;
    int i=firstMonday;
    while(i<maxDaysInMonth){
        mondays++;
        i+=7;
    };
    System.out.println(mondays);

答案 3 :(得分:0)

根据我的问题。

@Ramzan Zafar: 答案是正确的,因为我创建了当年和月份的年度和月份的日历实例。 根据我的问题,我得到了答案。