0

I've got two Dates and I want to compare them. I've logged the actual date to make sure its correct and it is.

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);
  }

For some reason the compareTo method is always returning -1 even if this date is not before the Date argument.

LuxuryMode
  • 33,401
  • 34
  • 117
  • 188
  • See also: http://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion – Vlad Aug 16 '11 at 20:16

3 Answers3

2

Date includes time down to milliseconds. You need to either use a different comparator or trim the time information:

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);
Vlad
  • 10,602
  • 2
  • 36
  • 38
  • Thanks, Vlad. I appreciate it. I tried that but it didn't seem to work. Maybe because I had to actual cast that to an int (even though it was declared as an int) – LuxuryMode Aug 16 '11 at 20:25
  • @LuxuryMode: Actually it needs to be cast to `long` since Math.floor() returns double. Updated. – Vlad Aug 16 '11 at 20:30
1

That is the expected behavior, it returns -1 if the argument is after the date.

Date compareTo

Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
0

Another solution is that since you only wish to compare the day,month&year , you should create a clone of the other date , and set the day,month,year according to what you need

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

and then use the comparison.

An example function for comparing 2 dates using only their day,month,year is :

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);
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270