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

Seyed Vahid Hashemi:

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

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

Jan Vorcak:

您可以像这样逐个比较价值

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在bash脚本中比较两个日期?

如何在Django中比较两个日期时间

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

如何在razor mvc中比较两个日期?

如何在Java中比较两个日期和时间

如何在Maven应用程序Java中比较两个日期

如何在Java中比较两个日期,然后将结果与另一个日期比较?

如何在Java中比较两个double值?

如何在Java中比较两个对象数组?

如何在Java中比较两个URL?

如何在Java中比较两个ArrayList

如何在Java中比较两个HashMap

如何在Excel中的两个单元格中比较两个日期?

如何在Swift 3中比较两个日期(NSDate)并获取它们之间的日期?

如何在Tibco BW中比较两个日期和当前日期?

如何在Java 8中比较两个日期之间的分钟差异,同时还要考虑时区差异?

datetime如何工作以及如何在Windows窗体ADO Entities中比较两个日期?

如何在查询中比较两个日期和时间

如何在jQuery中比较月份和年份的两个日期

如何在JavaScript中比较yy-dd-mm格式的两个日期?

如何在Power Bi查询中比较两个日期

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

如何在PowerShell中比较两个日期并在数分钟内获得差异

如何在Yii中比较两个日期并更新模型数据

如何在SQL的同一列中比较两个日期

在mysql中比较两个日期

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

如何在JUnit中比较两个double列表

如何在C ++中比较两个char数组?