Date compareTo() method always returning -1
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.
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);
That is the expected behavior, it returns -1 if the argument is after the date.
Date compareTo
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);
}
精彩评论