public int compareTo(Date anotherDate) Compares two Dates for ordering.Parameters:anotherDate - the Date to be compared.Returns:the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument
public int compareTo(Date anotherDate)是不行的,因为Date对象是精确到毫秒的,所以是同一天的两个Date对象并不一定会相等。 分别取出年月日来判断也不好,因为那些方法都已经被弃用了。 可以考虑先转化成字符串再进行比较: boolean isSameDay(Date date1,Date date2) { String DATE_FORMAT = "yyyy-MM-dd"; java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT); date1Str = sdf.format(date1); date2Str = sdf.format(date2); return date1Str.equals(date2Str); }
java.util.Date的取年月日方法被deprecated了,但却replaced by java.util.Calendar的啊,看看api documentation,java中有api为什么不用,而去找麻烦,“简单是可靠性的前提”---dijkstra
分别取出年月日来判断也不好,因为那些方法都已经被弃用了。
可以考虑先转化成字符串再进行比较:
boolean isSameDay(Date date1,Date date2) {
String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
date1Str = sdf.format(date1);
date2Str = sdf.format(date2);
return date1Str.equals(date2Str);
}