2012-01-06 82 views
0

我想比較給定期間內的日期。 我使用之前和之後的方法。 這裏是我的方法。比較給定期間內的日期

public boolean compareDatePeriod() throws ParseException 
{ 
    [.....] 
    if (period.getDateStart().after(dateLine)){ 
     if (period.getDateEnd().before(dateLine)){ 
      result = true; 
      } 
     } 
    ; 
    return result; 
} 

if my dateLine =「01/01/2012」and my period.getDateStart()=「01/01/2012」。 我返回false。我不懂爲什麼?

+0

什麼是你'period'的數據類型和'dartLine'? – Vaandu 2012-01-06 10:18:38

+0

你的期間和dartLine的數據類型:日期 – Mercer 2012-01-06 10:29:27

回答

1
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); 
    Date startDate = dateFormat.parse("01/01/2012"); 
    Date endDate = dateFormat.parse("31/12/2012"); 
    Date dateLine = dateFormat.parse("01/01/2012"); 
    boolean result = false;  
    if ((startDate.equals(dateLine) || !endDate.equals(dateLine)) 
      || (startDate.after(dateLine) && endDate.before(dateLine))) { // equal to start or end date or with in period 
     result = true; 
    } 
    System.out.println(result); 
+1

他沒有要求密碼,他只是問爲什麼不按照他想要的方式行事。但他選擇了你的答案。 :) – 2012-01-06 11:22:13

+0

:)在我的代碼中添加了評論,我試過了。 – Vaandu 2012-01-06 11:24:10

+0

試過了什麼?你懶洋洋地幫助了他,我敢打賭,他仍然沒有明白爲什麼它不起作用。我所說的是,在StackOVerflow中回答問題的目的是幫助提問者找出錯誤,而不是爲他編寫代碼,並使他在將來也犯同樣的錯誤。這是我唯一說的 – 2012-01-06 11:26:09

1

如果你想懇請您的問題發佈前檢查Java documentation,你就會知道,after返回方法:

當且僅當此Date對象表示的瞬間是 嚴格晚於瞬間由何時代表;否則爲假。

在你的情況,日期是等於,這意味着他們沒有strictly later。因此,它會返回false

UPDATE:

public boolean compareDatePeriod() throws ParseException 
{ 
    [.....] 
    if (!period.getDateStart().equals(dateLine)) { 
     if (period.getDateStart().after(dateLine)){ 
      if (period.getDateEnd().before(dateLine)){ 
       result = true; 
       } 
      } 
    return result; 
} 
+0

那麼你如何管理這種情況 – Mercer 2012-01-06 10:21:02

+0

你首先測試它們是否相等,如果不是,你做你的正常測試 – 2012-01-06 10:21:43

+0

檢查我更新的答案 – 2012-01-06 10:23:27