我想你忘了检查日期毫秒是否相同。
这是 compareTo 方法的源代码。
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
如您所见,此方法使用毫秒作为“时间步长”比较两个日期。
旧 API 的代码:
此代码检查两天是否相同。 (不包括小时、分钟、秒和毫秒)
Date date1; //Your initial date
Date date2; //Your initial second date
//Remove hours, minutes, seconds and milliseconds by creating new "clean" Date objects
Date compare1 = new Date(date1.getYear(), date1.getMonth(), date1.getDay());
Date compare2 = new Date(date2.getYear(), date2.getMonth(), date2.getDay());
if(compare1.compareTo(compare2) == 0){
}
但我建议您不要在此任务中使用 Date。因为 getYear、getMonth 等方法已被弃用,我建议您查看更新的 API,例如 GregorianCalendar 和 Calendar
新 API 的代码
此代码检查两天是否相同,包括小时和分钟。但没有秒和毫秒。
Date date1;
Date date2;
Calendar compareCalendar1 = Calendar.getInstance();
Calendar compareCalendar2 = Calendar.getInstance();
compareCalendar1.setTime(date1);
compareCalendar2.setTime(date2);
//Set for both calendars the seconds and milliseconds to 0
compareCalendar1.set(Calendar.MILLISECOND, 0);
compareCalendar1.set(Calendar.SECOND, 0);
compareCalendar2.set(Calendar.MILLISECOND, 0);
compareCalendar2.set(Calendar.SECOND, 0);
if(compareCalendar1.compareTo(compareCalendar2) == 0){
}