如何计算一个月内的星期二数?

时间:2012-05-03 09:39:52

标签: java calendar

如何计算一个月内星期二的数量?

使用calender.set我们可以设置特定月份,之后如何计算当月的星期一,星期二等数量?

代码是:

public static void main(String[] args )
{
    Calendar calendar = Calendar.getInstance();
    int  month = calendar.MAY; 
    int year = 2012;
    int date = 1 ;

    calendar.set(year, month, date);

    int MaxDay = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
    int mon=0;

    for(int i = 1 ; i < MaxDay ; i++)
    {        
        calendar.set(Calendar.DAY_OF_MONTH, i);
        if (calendar.get(Calendar.DAY_OF_WEEK) == calendar.MONDAY ) 
            mon++;      
    }

    System.out.println("days  : " + MaxDay);    
    System.out.println("MOndays  :" + mon);
}

4 个答案:

答案 0 :(得分:8)

这里没有编写完整的代码是一般的想法:

    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, Calendar.MAY); // may is just an example
    c.set(Calendar.YEAR, 2012);
    int th = 0;
    int maxDayInMonth = c.getMaximum(Calendar.MONTH);
    for (int d = 1;  d <= maxDayInMonth;  d++) {
        c.set(Calendar.DAY_OF_MONTH, d);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        if (Calendar.THURSDAY == dayOfWeek) {
            th++;
        }
    }

此代码应计算星期四的数量。我相信你可以修改它来计算一周中所有天数。

显然这段代码效率不高。它迭代了一个月的所有日子。您可以通过获取第一天的星期几,月中的天数以及(我相信)您可以编写计算每周某一天的数量而不会在整个月内迭代的代码来优化它。

答案 1 :(得分:3)

使用Java 8+,您可以用更简洁的方式编写它:

public static int countDayOccurenceInMonth(DayOfWeek dow, YearMonth month) {
  LocalDate start = month.atDay(1).with(TemporalAdjusters.nextOrSame(dow));
  return (int) ChronoUnit.WEEKS.between(start, month.atEndOfMonth()) + 1;
}

您可以致电:

int count = countDayOccurenceInMonth(DayOfWeek.TUESDAY, YearMonth.of(2012, 1));
System.out.println(count); //prints 5

答案 2 :(得分:0)

AlexR提到了更高效的版本。以为我会给它一个旋转:

private int getNumThursdays() {
    // create instance of Gregorian calendar 
    Calendar gc = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
    int currentWeekday = gc.get(Calendar.DAY_OF_WEEK);

    // get number of days left in month
    int daysLeft = gc.getActualMaximum(Calendar.DAY_OF_MONTH) - 
            gc.get(Calendar.DAY_OF_MONTH);

    // move to closest thursday (either today or ahead)
    while(currentWeekday != Calendar.THURSDAY) {
        if (currentWeekday < 7)  currentWeekday++;
        else currentWeekday = 1;
        daysLeft--;
    }

    // calculate the number of Thursdays left
    return daysLeft / 7 + 1;
}

注意:获取当前年,月,日等时,取决于您的环境。例如,如果有人手动将手机上的时间设置为错误,那么这种计算可能是错误的。为确保正确性,最好从可靠来源提取当前月,年,日,时间的数据。

答案 3 :(得分:0)

Java日历实际上具有Calendar.DAY_OF_WEEK_IN_MONTH

的内置属性
Calendar calendar = Calendar.getInstance(); //get instance
calendar.set(Calendar.DAY_OF_WEEK, 3);  //make it be a Tuesday (crucial)
//optionally set the month you want here
calendar.set(Calendar.MONTH, 4) //May
calendar.getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for this month (what you want)
calendar.getMaximum(Calendar.DAY_OF_WEEK_IN_MONTH); //for any month (not so useful)