2012-05-03 73 views
-1

如何計算一個月的星期二數?如何計算一個月的星期二數量?

使用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); 
} 
+0

你有日期,如果你知道如果它的mod比mod更7。 –

回答

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++; 
     } 
    } 

此代碼應該算週四的數量。我相信你可以修改它來統計每週的所有天數。

顯然這段代碼效率不高。它遍歷本月的所有日子。您可以通過獲取第一天的星期幾,月中的天數以及(我相信),您可以優化它,您可以編寫代碼來計算每週的每天數量,而無需重複整個月。

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; 
} 

注意:獲取當前的年份,月份,日期等,這取決於您的環境。例如,如果某人手動設置了手機上的時間出錯,那麼這種計算可能是錯誤的。爲確保正確性,最好從可信來源獲取有關當前月份,年份,日期和時間的數據。

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) 
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 
相關問題