2011-01-14 148 views
0

我寫了這個代碼和它不工作......日曆比較不工作

銦酸=「13/1/2011」

Calendar cd1 = Calendar.getInstance(); 
     String[] StartDate = split(inDate.trim(),"/"); 
     cd1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(StartDate[0])); 
     cd1.set(Calendar.MONTH, Integer.parseInt(StartDate[1])); 
     cd1.set(Calendar.YEAR, Integer.parseInt(StartDate[2])); 

currentDate ="14/1/2011" 
     String CurrentDate = com.connection.loginscreen.currentDate; 
     Calendar cd2 = Calendar.getInstance(); 
     String[] resultc = split(CurrentDate.trim(), "/"); 
     cd2.set(Calendar.YEAR, Integer.parseInt(resultc[2])); 
     cd2.set(Calendar.MONTH, Integer.parseInt(resultc[0])); 
     cd2.set(Calendar.DAY_OF_MONTH, Integer.parseInt(resultc[1])); 

     if (cd1.before(cd2)) 
     { 
      check ="1"; 
     } 

它不工作... ..

+0

它工作...? – 2011-01-14 07:12:50

+0

抱歉,當前日期爲2011年1月14日。 – Sourabh 2011-01-14 07:24:33

回答

1

不要自己解析。將字符串轉換爲日期,使用日期格式一個,像這樣:

DateFormat f = new SimpleDateFormat("dd/M/yyyy"); 
    String indate = "13/1/2011"; 
    Date cd1 = f.parse(indate); 
    String currentDate ="1/14/2011"; 
    DateFormat f2 = new SimpleDateFormat("M/dd/yyyy"); 
    Date cd2 = f2.parse(currentDate); 
    if (cd1.before(cd2)) 
    { 
     check ="1"; 
    } 

檢查SimpleDateFormat javadocs看到的圖案定義了什麼以及如何使用它。

3

這是幾乎可以肯定不是你想要的東西:

cd1.set(Calendar.MONTH, Integer.parseInt(StartDate[1])); 

Calendar.MONTH是從零開始......而人類通常的讀/以基於1的方式寫月份。

儘管沒有詳細說明,但你真的不應該自己編寫解析代碼,除非你有一個奇怪的格式,它不是由庫處理的,除非你有一個特別的。如果您確實想要堅持使用Java庫,請使用SimpleDateFormat來解析它。自己解析會導致類似上面的錯誤和jk指出的錯誤。這就像是從字符串手工構建XML:不這樣做 - 使用庫

個人而言,我建議使用Joda Time在Java中的所有日期/時間工作。這是一個更好的API。