java - 如何比较java中的两个日期?

标签 java date comparison

我正在尝试比较两个日期,我只想比较日期部分而不是时间部分这就是我在程序中存储日期的方式:

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

最佳答案

你可以像这样逐个比较

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

关于java - 如何比较java中的两个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8367936/

相关文章:

java - BST 数据结构 -- 类项目 -- 访问嵌套类

java - 有人可以向我解释这段使用移位将两个变量相乘的代码吗?

html - 如何让这两个日历并排显示?

spring - elasticsearch-如何找到确切的日期类型值?

string - 可以直接比较存储为字符串/文本的日期吗?

python - 比较 2 个词典列表,并将一个列表中缺失(不匹配)的词典添加到另一个列表中

java - Resttemplate 的 utf-8 编码 url 参数

java - 接受多部分文件的 DELETE 方法的 Mockmvc

excel - 根据颜色和日期对单元格求和

javascript - 大于/小于运算符在 Q Promise 上的行为与等于运算符不同