2016-11-21 139 views
0

我只需要今天和昨天的日期和其他日期選擇它應該給錯誤....我得到的每一件事情確定,但有小問題 這裏是我的代碼:問題在越來越差日期

if (flag == 0) { 
      if (getday(myCalendar.getTime()) == 1 || getday(myCalendar.getTime()) == 0) { 
       setvisitdate(); 
      } 
       Toast.makeText(getApplicationContext(), 
         "Selected date is not valid...", Toast.LENGTH_SHORT) 
         .show(); 

       flag = 0; 
       new DatePickerDialog(FvrActivity.this, date, 
         myCalendar.get(Calendar.YEAR), 
         myCalendar.get(Calendar.MONTH), 
         myCalendar.get(Calendar.DAY_OF_MONTH)).show(); 
      } 

這裏是getday的方法:

private int getday(Date selected_date) { 

     Calendar selected_cal = Calendar.getInstance(); 
     selected_cal .setTime(selected_date); 
     Calendar c = Calendar.getInstance(); 
     c.getTime(); 
     long diffInMillisec = c.getTimeInMillis() - selected_cal.getTimeInMillis(); 
     long diffInDays = TimeUnit.MILLISECONDS.toDays(diffInMillisec); 
     return (int) diffInDays; 
    } 

假設今天的日期是21/11/2016 ...我只是想選擇21日和20,而不是22,但在這裏,我可以選擇22 also..Thank你提前解決。

+0

beetween 22和21的區別也一天。猜你可以添加.above()\ .belowe()檢查。也日期類將是足夠的。例如,新的Date()會獲取當前日期。 – user5599807

回答

1

使用此邏輯:

Calendar selected_cal = Calendar.getInstance(); 
selected_cal.setTime(selected_date); 

//For next day     
Calendar nextDay = Calendar.getInstance(); 
nextDay.add(Calendar.DATE, 1);//Adding one day 
nextDay.set(Calendar.HOUR_OF_DAY, 0);//Setting calendar for start hour of the day 
nextDay.set(Calendar.MINUTE, 0);//Setting calendar for start minute of the day 
nextDay.set(Calendar.SECOND, 0);//Setting calendar for start second of the day 

//For previous days 
Calendar previousDay = Calendar.getInstance(); 
previousDay.add(Calendar.DATE, -2);//Adding one day 
previousDay.set(Calendar.HOUR_OF_DAY, 23);//Setting calendar for start hour of the day 
previousDay.set(Calendar.MINUTE, 59);//Setting calendar for start minute of the day 
previousDay.set(Calendar.SECOND, 59);//Setting calendar for start second of the day 

if(selected_cal.getTimeInMillis()>=nextDay.getTimeInMillis() 
|| selected_cal.getTimeInMillis()<previousDay.getTimeInMillis()){ 
     //Show error 
}else{ 
     //Do what you want to do 
}