您可以像这样逐个比较值。
d1.getDate().equals(d2.getDate()) &&
d1.getYear().equals(d2.getYear()) &&
d1.getMonth().equals(d2.getMonth())
或者
Date date1 = new Date(d1.getYear(), d1.getMonth(), d1.getDate());
Date date2 = new Date(d2.getYear(), d2.getMonth(), d2.getDate());
date1.compareTo(date2);
如果您正在使用Date类,请考虑改用Calendar类。以下是最优雅的解决方案,使用Calendar和Comparator实现此功能。
public class CalendarDateWithoutTimeComparator implements Comparator<Calendar> {
public int compare(Calendar cal1, Calendar cal2) {
if(cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)) {
return cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
} else if (cal1.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)) {
return cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
}
return cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
}
}
使用方法:
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
CalendarDateWithoutTimeComparator comparator = new CalendarDateWithoutTimeComparator();
System.out.println(comparator.compare(c1, c2));
List<Calendar> list = new ArrayList<Calendar>();
list.add(c1);
list.add(c2);
Collections.sort(list, comparator);