2016-10-19 255 views
-2

我從日曆中得到兩個日期。它寫入一個字符串builder.I想要獲得兩個日期之間的差異,我還想保持時間之間的剩餘天數,除了週末。兩個日期之間的Android差異?

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() { 

     // when dialog box is closed, below method will be called. 
     public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) { 


      year = selectedYear; 
      month = selectedMonth; 
      day = selectedDay; 

      if (cur == DATE_DIALOG_ID) { 
       // set selected date into textview 
       permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString(); 
       tvDisplayDate.setText("Date : " + permitDate); 

      } else { 
       startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString(); 
       tvDisplayDate2.setText("Date : " + startDate); 


      } 

     } 
    }; 
+1

這樣認爲你應該使用java的日曆API – Jens

+0

我可以不使用API​​日曆嗎? –

+0

不要試圖重新發明輪子。建立在現有解決方案上像AndroidThreeTenBp或Joda時間。你會減少你將你的頭撞在牆上的次數。 –

回答

0
Calendar thatDay = Calendar.getInstance(); 
thatDay.set(Calendar.DAY_OF_MONTH,25); 
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less 
thatDay.set(Calendar.YEAR, 1985); 

Calendar today = Calendar.getInstance(); 

long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis 

long days = diff/(24 * 60 * 60 * 1000); 

從字符串解析日期,你可以使用

String strThatDay = "1985/08/25"; 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); 
Date d = null; 
try { 
d = formatter.parse(strThatDay);//catch exception 
} catch (ParseException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 


Calendar thatDay = Calendar.getInstance(); 
thatDay.setTime(d); //rest is the same.... 
0

使用JodaTime庫中查找日期之間的差值。 欲瞭解更多信息,請按照說明Use Joda Time