2011-07-07 18 views
2

我在嘗試比較Android中的兩個日期時出現問題。我不確定它是否是模擬器的問題,或者如果我在代碼本身存在問題。 事情是代碼在普通的Java程序環境中工作,這讓我更加困惑。在Android中比較日期(時間)的問題

我有下面的代碼在Android 2.1的比較日期:

public boolean compareDates(String givenDateString) { 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); 
    boolean True; 
    try { 
     True = false; 
     Date givenDate = sdf.parse(givenDateString); 
     Date currentDate = new Date(); 

     if(givenDate.after(currentDate)){ 
      True = true; 
     } if(givenDate.before(currentDate)){ 
      True = false; 
     } if(givenDate.equals(currentDate)){ 
      True = false; 
     } 
    } catch (Exception e) { 
     Log.e("ERROR! - comparing DATES", e.toString()); 
    } 
    return True; 
} 

現在的代碼工作在Java中,但在Android的它讓我返回假。

Date currentDate = sdf.parse("16:50"); 

隨着當我指定的時間之後,這是一個值進行比較,它返回true一個字符串的currentdate變量集: 唯一的變化,當我插入帶有這樣一個字符串變量的currentdate發生。我也嘗試設置currentDate變量:

Calendar calendar = Calendar.getInstance(); 
    Date currentDate = calendar.getTime(); 

我在這裏完全不知所措。希望有人對這裏可能存在的問題有任何想法。

---編輯---

發現我的問題的解決方案。我使用日曆並從那裏讀取小時和分鐘,然後我將它們放入一個字符串中進行解析並且工作。代碼現在看起來像這樣:

public boolean compareDates(String givenDateString) { 
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); 
    boolean True = false; 
    try { 
     Date givenDate = sdf.parse(givenDateString); 
     Calendar now = Calendar.getInstance(); 
      int hour = now.get(Calendar.HOUR_OF_DAY); 
      int minute = now.get(Calendar.MINUTE); 
     Date currentDate = sdf.parse(hour + ":" + minute); 

     if(givenDate.after(currentDate)){ 
      True = true; 
     } if(givenDate.before(currentDate)){ 
      True = false; 
     } if(givenDate.equals(currentDate)){ 
      True = false; 
     } 
    } catch (Exception e) { 
     Log.e("ERROR! - comparing DATES", e.toString()); 
    } 
    return True; 
} 

回答

0

當我在日期上進行比較時,我一定要使用Calendar對象。然後,我用的compareTo()函數:

if (myCalendar.compareTo(upperLimitCalendar) >= 0) 

在這裏看到的文檔:

http://developer.android.com/reference/java/util/Calendar.html

+0

謝謝你的答案。非常感激。我查了一下日曆,找到了解決問題的辦法。再次感謝。 –

+0

沒問題。很高興我能幫上忙。 – SBerg413