2013-12-09 119 views
1

我有2日期選擇器在我的活動中,1爲分配日期和其他是到期日期,現在我想要做的是當用戶設置的日期我想要區別文本視圖中的日期。Android - 如何減去任何其他日期的當前日期

Ex。如果分配日期爲12-05-2013,截止日期爲14-05-2013,那麼文本視圖應該顯示我已經完成的「2天左右」。

現在問題來了,當日期變化像今天是13-05-2013那麼我想在文本視圖中顯示「1日左」,這意味着文本視圖應該自動更新當前日期。

public class Code { 
public static Calendar AssignDate; 
public static Calendar DueDate; 
} 

imageViewSubmit.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View arg0) { 
      Code.title = editTextTitle.getText().toString().trim(); 
      Code.description = editTextDesc.getText().toString().trim(); 
      Code.diff = Code.DueDate.getTimeInMillis() 
        - Code.AssignDate.getTimeInMillis(); 
      Code.days = Code.diff/(24 * 60 * 60 * 1000); 

      String strDays = String.valueOf(Code.days); 
      textViewDiff.setText(strDays); 
      String dateDifference = textViewDiff.getText().toString().trim(); 
     } 
    });    

回答

0
String date1 = "12-05-2013"; 
String date2 = "14-05-2013"; 
Calendar date1Calendar = Calendar.getInstance(); 
date1Calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString)); 
Calendar date2Calendar = Calendar.getInstance(); 
date2Calendar.setTime(new SimpleDateFormat("dd-MM-yyyy").parse(inputDateString)); 
if(date2Calendar.after(date1Calendar)) 
    String daysLeft = "Days Left: " + (date2Calendar.get(Calendar.DAY_OF_MONTH) -(date1Calendar.get(Calendar.DAY_OF_MONTH))); 
1

希望這個例子可以幫助你。

import java.text.SimpleDateFormat; 
import java.util.Date; 

public class DateDifferenceExample { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 

     String dateStart = "12/09/2013 09:29:58"; 
     String dateStop = "12/15/2013 10:31:48"; 

     // HH converts hour in 24 hours format (0-23), day calculation 
     SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 

     Date d1 = null; 
     Date d2 = null; 

     try { 
      d1 = format.parse(dateStart); 
      d2 = format.parse(dateStop); 

      // in milliseconds 
      long diff = d2.getTime() - d1.getTime(); 

      long diffSeconds = diff/1000 % 60; 
      long diffMinutes = diff/(60 * 1000) % 60; 
      long diffHours = diff/(60 * 60 * 1000) % 24; 
      long diffDays = diff/(24 * 60 * 60 * 1000); 

      System.out.print(diffDays + " days, "); 
      System.out.print(diffHours + " hours, "); 
      System.out.print(diffMinutes + " minutes, "); 
      System.out.print(diffSeconds + " seconds."); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

}