2015-11-08 145 views
0

我試圖比較日期以找到與當前日期(今天的日期)相距最近的兩個日期。但是,我沒有使用Date.before()獲得預期的結果。Date1.before(Date2)未返回預期結果

代碼在這裏:

Date currentDate; 
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM"); 

public Date getDate(){ 
    currentDate = new Date(); 
    //Toast.makeText(Happenings.this, currentDate, Toast.LENGTH_SHORT).show(); 
    return currentDate; 
} 

public String[] compareDate(Date currentDate){ 
    String[] closestDates = new String[2]; 
    //Toast.makeText(Happenings.this, sdf.format(currentDate), Toast.LENGTH_SHORT).show(); 
    try { 
     Date date1 = sdf.parse("20/01"); 
     Date date2 = sdf.parse("09/08"); 
     Date date3 = sdf.parse("24/12"); 
     Date[] availableDates = {date1, date2, date3}; // dd/mm 
     //Toast.makeText(Happenings.this, sdf.format(date1), Toast.LENGTH_SHORT).show(); 
     if (currentDate.before(date3)) { 
      Toast toast = Toast.makeText(Happenings.this, "Before Festival", Toast.LENGTH_SHORT); 
      toast.show(); 
     } 
    } 
    catch (ParseException e){ 
     Toast.makeText(Happenings.this, "Catch", Toast.LENGTH_SHORT).show(); 
     e.printStackTrace(); 
    } 


    return closestDates; 
} 

我現在我得到的是currentDate.before(DATE3)計算爲false和currentDate.after(DATE3)評估爲true。這與08/11之前的預期不同,應該在24/12之前。

回答

0

我可能是錯的,但如果你嘗試使用date2.before(date3)並且它將評估爲true,那麼我會猜測簡單地解析日期和月份將默認1970年設置爲當年而不是當前年份。 如果是這種情況,那麼我建議你手動設置年份,或者將年份添加到sdf。