2010-02-27 62 views
3

我想比較兩個日期時間,但我無法讓它工作。Android的比較日期時間

public void time() { 
     Calendar c11 = Calendar.getInstance(); 
     c11.add(Calendar.DAY_OF_YEAR, 0); 
     c11.set(Calendar.HOUR_OF_DAY, 9); 
     c11.set(Calendar.MINUTE, 0); 
     c11.set(Calendar.SECOND, 0); 

     Calendar c12 = Calendar.getInstance(); 
     c12.add(Calendar.DAY_OF_YEAR, 0); 
     c12.set(Calendar.HOUR_OF_DAY, 9); 
     c12.set(Calendar.MINUTE, 0); 
     c12.set(Calendar.SECOND, 0); 

     c11.getTime(); 
     c12.getTime(); 
     boolean k = c11.equals(c12); 
     if (k==true) 
     { 
      Toast.makeText(
       getContext(), 
       "Wow these two times are the same!", 
       Toast.LENGTH_LONG).show(); 
     } 
    } 
    } 

回答

3
  1. 2個時間值的毫秒是不同的,因此相等比較會返回false。

  2. 爲什麼要在兩個日曆實例中添加0天?那什麼都不做。

+0

爲什麼值不同的C11和C12都設置成一樣的嗎? – SamB09 2010-02-27 17:11:41

+0

不,他們不一樣。就像我剛纔所說的那樣,毫秒是不同的。您需要將毫秒設置爲0。現在毫秒被設置爲當你調用Calendar.getInstance()時的當前時間。 – 2010-02-27 17:53:21

+0

對,有沒有其他辦法可以比較這兩個? – SamB09 2010-02-27 18:13:10

1
public void onDateSelected(DateTime dateSelected) { 
    DateTime currentDateTime = new DateTime(); 

    try{ 
     /* If you want to compare only date from DateTime object then, 
      you can use "yyyy-MM-dd" format and split the string from T like: 
      dateSelected.toString().split("T") and use str1[0] to parse */ 

     SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"); 

     String str1 = dateSelected.toString(); 
     Date selectedDate = formatter.parse(str1); 

     String str2 = currentDateTime.toString(); 
     Date currentDate = formatter.parse(str2); 

     if (selectedDate.compareTo(currentDate)<0) 
     { 
      System.out.println("current date is Greater than my selected date"); 
     } 

    }catch (ParseException e1){ 
     e1.printStackTrace(); 
    } 
} 
+1

我們可以發送格式作爲這個函數的參數,使它更通用? public void onDateSelected(DateTime dateSelected,String format)SimpleDateFormat formatter = new SimpleDateFormat(format); ... } – Fahad 2017-11-28 13:10:33

+1

是的,你可以這樣做:) – 2017-11-28 13:11:25

+0

謝謝Shujat它會幫助 – Fahad 2017-11-28 13:16:25