2016-08-27 136 views
1

我試圖在我的日曆中禁用星期六和星期日。要做到這一點,我必須找到它。我嘗試過,但我無法得到它。在這裏我發佈了代碼。如何在android中查找當前星期六和星期天?

public int countWeekendDays() { 
    Calendar calendar = Calendar.getInstance(); 

    calendar.set(Calendar.DAY_OF_WEEK, Calendar.DATE+1); 
    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 

    int count = 0; 
    for (int day = 1; day <= daysInMonth; day++) { 
     calendar.set(Calendar.DAY_OF_WEEK, Calendar.DATE+1, day); 
     int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); 
     if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) { 
      if(dayOfWeek==Calendar.SUNDAY) 
       calendar.add(Calendar.DATE, Calendar.SUNDAY-1); 
      else if(dayOfWeek==Calendar.SATURDAY) 
       calendar.add(Calendar.DATE, Calendar.SATURDAY); 

      disable.add(calendar.getTime()); 
     } 

    } 
    for(int i=0;i<disable.size();i++) 
    { 
     Log.e("***&***",disable.get(i).toString()); 
    } 
    return count; 
} 

我需要獲得當前月的週六和週日(大寫:8月),但我所得到的結果是前一個月,即月。

+0

這個問題重複*在堆棧溢出許多*人獲取當前月份,獲得的第一天和最後一天一個月,並檢測每個星期六或星期日或工作日(等)。 –

回答

3

試試這個:

List<Date> disable = new ArrayList<>(); 

Calendar cal = Calendar.getInstance(); 
cal.set(Calendar.DAY_OF_MONTH, 1); 
int month = cal.get(Calendar.MONTH); 
do { 
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); 
    if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) 
     disable.add(cal.getTime()); 
    cal.add(Calendar.DAY_OF_MONTH, 1); 
} while (cal.get(Calendar.MONTH) == month); 

SimpleDateFormat fmt = new SimpleDateFormat("EEE M/d/yyyy"); 
for (Date date : disable) 
    System.out.println(fmt.format(date)); 

輸出

Sat 8/6/2016 
Sun 8/7/2016 
Sat 8/13/2016 
Sun 8/14/2016 
Sat 8/20/2016 
Sun 8/21/2016 
Sat 8/27/2016 
Sun 8/28/2016 
+0

其工作...感謝兄弟 –

2
public static ArrayList<Calendar> getAllSundayDate(Calendar aCurrentDateCal, int aMaxMonth){ 
    //max month next month for Exp: next 2 month from this month 
    ArrayList<Calendar> disableDayList = new ArrayList<>(); 
    Calendar cal; 
    cal = aCurrentDateCal; 
    for (int index = 0; index < aMaxMonth; index++) { 
     int year = cal.get(Calendar.YEAR); 
     int month = cal.get(Calendar.MONTH); 
     Calendar curCal = Calendar.getInstance(); 
     curCal.set(year, month , 1); 
     int daysInMonth = curCal.getActualMaximum(Calendar.DAY_OF_MONTH); 

     for (int day = 1; day <= daysInMonth; day++) { 
      curCal.set(year, month, day); 
      int dayOfWeek = curCal.get(Calendar.DAY_OF_WEEK); 
      if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) { 
       disableDayList.add(curCal); 
       Date curDate = new Date(curCal.getTimeInMillis()); 
       System.out.println(curDate); 
      } 
     } 

     cal.add(Calendar.MONTH, 1); 
    } 
    return disableDayList; 
} 
+1

請解釋一下你的代碼 – karan

相關問題