如何在 Java 中比较两个日期?

4

我正在尝试将两个日期进行比较,只希望比较日期部分而不是时间部分。这是我在程序中存储日期的方式:

Thu Jan 27 23:20:00 GMT 2011

我有一个:

ArrayList<Date> dateList;

我想使用

dateList.compares(newDate);
// if the answer was false which means I 
// have new date then add the newdate to my list

但由于时间部分也涉及在内,我无法得到正确的答案。如何解决我的问题?

我不想使用JODA-TIME。

4个回答

3
您可以像这样逐个比较值。
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();
// these calendars are equal

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

2
为什么不使用compareTo()方法?
int java.util.Date#compareTo(Date anotherDate)

0
Date check_in = new Date(2010,7,31);
Date check_out = new Date(2011,5,22);

int result = check_out.compareTo(check_in); 

if(result<0)
{
  // check_out < check_in
}
else if(result>0)
{
 // check_out > check_in
}
else
{
// check_out == check_in
}       

0

你可以使用这个

int compareDates(Calendar c1, Calendar c2) {
    if(c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)){
        return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
    } else if(c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH)){
        return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
    }
    return (c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH));
}

编辑:

Joda 时间或没有,这篇 StackOverflow 帖子包含了有关日期比较的所有答案。

如何比较两个日期而不考虑时间部分?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接