2012-08-11 65 views
2

我變得有點粘在Java/Android的Calendar.before()和Calendar.after()返回不正確的值

  DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm"); 
       Calendar now = Calendar.getInstance(); 
       Calendar c; 

       c = Calendar.getInstance(); 
       c.set(settings.getInt("year", 0), settings.getInt("month", 0), settings.getInt("day", 0), settings.getInt("hour", 0), settings.getInt("minute", 0)); 

       views.setTextViewText(R.id.textView4, String.valueOf(c.getTime().before(now.getTime()))); 
       views.setTextViewText(R.id.textView2, String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime()))); 

       int timeout = 0; 
       while(c.getTime().before(now.getTime())) 
       { 
        c.add(Calendar.SECOND, 30); 
        c.add(Calendar.MINUTE, 12); 
        c.add(Calendar.HOUR_OF_DAY, 6); 
        isHigh = 1 - isHigh; 
        timeout++; 
        if(timeout >= 400) 
         break; 
       } 
       views.setTextViewText(R.id.textView5, String.valueOf(c.getTime().before(now.getTime()))); 
       views.setTextViewText(R.id.textView3, String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime()))); 

日期比較的這種想法是它需要一個起始日期從保存設置,並將6:12:30添加到時鐘,直到它超過當前時間。

然而,我的文本框給我下面的:

假:09/07/12 04:20 - 12年11月8日00:00

錯誤:09/07/12 04 :20 - 11/08/12 00:00

2012年7月9日爲什麼在2012年8月11日之前打電話時返回虛假?

如果我改變了 「之前」 到 「經過」,我得到這個:

真:09/07/12 04:20 - 12年11月8日00:00

true:20/10/12 15:40 - 11/08/12 00:00

這似乎沒有任何意義。

任何想法我做錯了什麼?謝謝

+0

嘗試對兩個日期進行logCat,然後再比較它們併發布結果。 – iTurki 2012-08-11 19:42:12

回答

6

我想知道是不是因爲你的「年」設置是12而不是2012年。那麼你會比較09/07/2012和11/08/0012 - 但你不能說因爲你的日期格式。

出於診斷目的,請將格式字符串更改爲"dd/MM/yyyy HH:mm",然後重試。

+0

是的,它向我展示了一年的「53312」......我不知道它從哪裏來,但顯然是原因。謝謝 – 2012-08-11 21:05:09

0

那麼,它的工作如預期在JDK與12以及2012年

DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm"); 
Calendar now = Calendar.getInstance(); 
Calendar c; 
c = Calendar.getInstance(); 
c.set(12, 6, 9, 0, 0); 
System.out.println(String.valueOf(c.getTime().before(now.getTime()))); 
System.out.println(String.format("%s - %s", df.format(c.getTime()), df.format(now.getTime()))); 

輸出: - 真正 09/07/12 00:00 - 12年11月8日13:29

-1

我之前有過這個問題。但我不需要比較小時,分鐘和秒鐘。只有約會。但@Jon Skeet的回答並不適合我。所以我已經實現了我自己的方法來比較兩個日期。醜,但工作正常。

private boolean before(Calendar c1, Calendar c2){ 
     int c1Year = c1.get(Calendar.YEAR); 
     int c1Month = c1.get(Calendar.MONTH); 
     int c1Day = c1.get(Calendar.DAY_OF_MONTH); 

     int c2Year = c2.get(Calendar.YEAR); 
     int c2Month = c2.get(Calendar.MONTH); 
     int c2Day = c2.get(Calendar.DAY_OF_MONTH); 

     if(c1Year<c2Year){ 
      return true; 
     }else if (c1Year>c2Year){ 
      return false; 
     }else{ 
      if(c1Month>c2Month){ 
       return false; 
      }else if(c1Month<c2Month){ 
       return true; 
      }else{ 
       if(c1Day<c2Day){ 
        return true; 
       }else{ 
        return false; 
       } 
      } 
     } 
    }