2011-08-16 5 views
0

나는 두 개의 날짜가있어서이를 비교하려고합니다. 정확한 날짜인지 기록하기 위해 실제 날짜를 기록했습니다. date compareTo() 메서드는 항상 -1을 반환합니다.

Date photoDate = new Date(mPhotoObject.calendar.getTimeInMillis()); 

SimpleDateFormat dateFormat = new SimpleDateFormat("M.d.yy"); 


Log.v("photo date is", dateFormat.format(photoDate)); 
Date currentDate = new Date(Calendar.getInstance().getTimeInMillis()); 
Log.v("current date is", dateFormat.format(currentDate)); 
Log.v("date comparison", photoDate.compareTo(currentDate)+""); 

if(photoDate.compareTo(currentDate)<0) { 
    view.showFooButton(false); 
    } else { 
    view.showFooButton(true); 
    } 

은 어떤 이유로 compareTo 메소드는 항상 반환 -1이 날짜 하지 날짜 인수 이전 인 경우에도 마찬가지입니다.

+0

항목 : http://stackoverflow.com/questions/1439779/how-to-compare-two- 날짜 - 시간 - 부분 - – Vlad

답변

2

Date은 아래로 밀리 초 시간이 포함됩니다. 당신은 다른 비교를 사용하거나 시간 정보를 트림 중 하나가 필요합니다

final long millisPerDay= 24 * 60 * 60 * 1000; 
... 
Date photoDate = new Date((long)Math.floor(mPhotoObject.calendar.getTimeInMillis()/millisPerDay) * millisPerDay); 
... 
Date currentDate = new Date((long)Math.floor(Calendar.getInstance().getTimeInMillis()/millisPerDay) * millisPerDay); 
+0

감사합니다, 블라드. 감사합니다. 나는 그것을 시도했다. 그러나 그것은 일하는 것처럼 보이지 않았다. 어쩌면 내가 실제로 그것을 int로 선언해야했기 때문일 수도있다. (심지어 int로 선언되었지만) – LuxuryMode

+0

@LuxuryMode : Math.floor()가 double을 반환하기 때문에 실제로는 long으로 캐스트해야한다. 업데이트 됨. – Vlad

+0

매력처럼 작동했습니다. 고마워요, 선생님. – LuxuryMode

1

예상되는 동작이며, 인수가 날짜 이후 인 경우 -1을 반환합니다.

Date compareTo

+0

죄송합니다, 나는 다른 방향으로 그것을 의미합니다. ;) 나는 내 질문을 편집했다. – LuxuryMode

0

또 다른 해결책은 만 달에게, 하루 & 년을 비교하고자하기 때문에, 당신은 다른 날짜의 복제를 생성하고 설정해야한다는 것입니다 당신이 필요로하는 것에 따라 일, 달, 년

Date date=new Date(otherDate.getTime()); 
date.setDate(...); 
date.setMonth(...); 
date.setYear(...); 

그리고 나서 비교를 사용하십시오.

사용하여 두 날짜를 비교 예 기능 만 하루, 한달, 일년은 다음과 같습니다

public static int compareDatesOnly(final Date date1, final Date date2) { 
    final Date dateToCompare = new Date(date1.getTime()); 
    dateToCompare.setDate(date2.getDate()); 
    dateToCompare.setMonth(date2.getMonth()); 
    dateToCompare.setYear(date2.getYear()); 
    return date1.compareTo(dateToCompare); 
} 
관련 문제