2011-10-12 57 views
0

向每一位努力工作的開發者傳遞我的致敬,如何比較java中的兩個日期?

併爲每一位奮鬥者歡呼。

其實我來到這裏是因爲我被困在一個非常基本的問題。

我建立一個客戶端 - 服務器應用程序,並且我感到困惑如何從JTable中提取兩個日期之間的比較(最後,我從來沒有在任何操作上了車日期一般)。

我用這個代碼:

public static final String DATE_FORMAT_NOW = "yyyy-MM-dd"; 

    public static String now() { 
    Calendar cal = Calendar.getInstance(); 
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); 
    return sdf.format(cal.getTime()); 

    } 

public static void ColorTheCell2(JTable jTable2){ 
      jTable2.getColumn("Date d'expiration").setCellRenderer(
    new DefaultTableCellRenderer() { 

     @Override 
    public Component getTableCellRendererComponent 
    (JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column){ 

    Calendar datetable=Calendar.getInstance(); 

    String date=value.toString(); 
    String day=""+date.substring(8).toString(); 
    String month=""+date.substring(5, 7).toString(); 
    String year=""+date.substring(0,4).toString(); 

    datetable.set(Integer.parseInt(year),Integer.parseInt(month),Integer.parseInt(day)); 
    Calendar curdate=Calendar.getInstance(); 

    String date1=now(); 
    String day1=""+date1.substring(8).toString(); 
    String month1=""+date1.substring(5, 7).toString(); 
    String year1=""+date1.substring(0,4).toString(); 
       curdate.set(Integer.parseInt(year1),Integer.parseInt(month1)+1,Integer.parseInt(day1)); 


      if(datetable.before(curdate)){ 

       setText(value.toString()); 
       setBackground(Color.red); 
      } 
      else{ 
       setText(value.toString()); 
      } 

return this; 
} 
    }); 
    } 

謝謝您的時間。 最好的問候

+0

http://stackoverflow.com/questions/2592501/compare-dates-in-java –

+4

你的代碼是非常難讀,由於瘋狂的格式不一致。不要讓人們難以幫助你。 –

+0

爲了更好地提供幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。 (與展開代碼片斷相反)。請從邏輯上縮進代碼。 –

回答

3

Date實現Comparable接口,因此你可以使用的方法compareTo()兩個日期之間的比較。同樣的事情Calendar,只需使用其compareTo()方法

6

你不告訴值的單元格中的類型是什麼。如果它是一個字符串,那麼你做錯了:它應該是一個日期,並且渲染器應該使用DateFormat來呈現日期(除了設置適當的背景之外)。例如,這將允許按時間順序排序表而不是按字典。

如果它已經是一個日期,然後就與當前的日期進行比較,使用它的compareTo方法。

你現在()方法是很奇怪的,因爲它似乎返回一個字符串,而不是一個日期表示日期的適當類型是日期而不是字符串每次使用日期格式並使用DateFormat格式化每次需要它作爲字符串時不要做相反的操作(使用String並解析它 - 手動 - 每次你需要一個日期)

+0

+1進行廣泛的解釋。 Nitpicking(顯然是味道的問題,這是我的:-) - 比一般更喜歡特定於域的API,即比compareTo之前/之後。 – kleopatra

4

如果Object value值類型的Date然後將其轉換爲Date -

Date valDate = (Date) value; 

或者,如果它String然後解析Date出來的 -

Date valDate = new SimpleDateFormat("pattern in value").parse((String) value); 

獲取當前日期 -

Date currDate = new Date(); 

然後你可以使用任何的t在Date類,他下面的方法 -

  1. boolean after(Date when)
  2. boolean before(Date when)
  3. int compareTo(Date anotherDate)

例如

if(valDate.before(currDate)) { 

    //... 

API文檔:DateSimpleDateFormat

+0

+1,用於在推薦前後的域特定方法 – kleopatra