我想有一个compareTo方法来忽略java.util.Date的时间部分。我想有很多方法可以解决这个问题。最简单的方法是什么?


当前回答

如果你正在寻找一个简单的解决方案,但你不想从你的项目中更改已弃用的java.util.Date类,你可以将这个方法添加到你的项目中,并继续你的探索:

使用java.util.concurrent.TimeUnit

`

public boolean isSameDay(Date first, Date second) {
    long difference_In_Time = first.getTime() - second.getTime();
        // calculate difference in days
        long difference_In_Days = 
        TimeUnit
              .MILLISECONDS
              .toDays(difference_In_Time);
        if (difference_In_Days == 0) {
            return true;
        }
        return false;
    }

`

像这样实现它:

`

Date first = ...;
Date second = ...;
if (isSameDay(first, second)) {
    // congratulations, they are the same
}
else {
   // heads up champ, they are not the same
}

`

其他回答

恐怕没有一种方法可以比较两个日期,可以称之为“容易”或“简单”。

当比较两个精度降低的时间实例时(例如,只是比较日期),你必须考虑时区对比较的影响。

例如,如果date1指定发生在+2时区的事件,而date2指定发生在EST时区的事件,则必须注意正确理解比较的含义。

你的目的是要弄清楚这两件事是否发生在各自时区的同一日历日期?或者,您是否需要知道这两个日期是否属于特定时区(例如,UTC或您的本地TZ)中的相同日历日期。

一旦你弄清楚你想要比较的是什么,就只需要在适当的时区获得年-月-日三元组合并进行比较。

Joda时间可能使实际的比较操作看起来更简洁,但是比较的语义仍然需要您自己弄清楚。

已经提到了apache common -utils:

org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH)

给你Date对象,只包含日期,没有时间,你可以与Date. compareto进行比较

public static Date getZeroTimeDate(Date fecha) {
    Date res = fecha;
    Calendar calendar = Calendar.getInstance();

    calendar.setTime( fecha );
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    res = calendar.getTime();

    return res;
}

Date currentDate = getZeroTimeDate(new Date());// get current date   

这是解决这个问题最简单的方法。

如果你真的想使用java.util。约会时,你会这样做:

public class TimeIgnoringComparator implements Comparator<Date> {
  public int compare(Date d1, Date d2) {
    if (d1.getYear() != d2.getYear()) 
        return d1.getYear() - d2.getYear();
    if (d1.getMonth() != d2.getMonth()) 
        return d1.getMonth() - d2.getMonth();
    return d1.getDate() - d2.getDate();
  }
}

或者,使用Calendar代替(首选,因为getYear()等已弃用)

public class TimeIgnoringComparator implements Comparator<Calendar> {
  public int compare(Calendar c1, Calendar c2) {
    if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR)) 
        return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
    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 Time在当时是一个很好的建议,使用java。在可能的情况下,从Java 8+替代时间库。


我倾向于使用Joda Time,这让这变得非常简单:

DateTime first = ...;
DateTime second = ...;

LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();

return firstDate.compareTo(secondDate);

编辑:正如评论中提到的,如果你使用DateTimeComparator.getDateOnlyInstance(),它甚至更简单:)

// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);

(“使用Joda Time”是几乎所有SO问题的基础,这些问题询问java.util.Date或java.util.Calendar。这是一个非常优秀的API。如果你要用日期/时间做任何重要的事情,你应该尽可能地使用它。)

如果必须使用内置API,则应该使用适当的日期和时区创建Calendar实例。然后,您可以将每个日历中的每个字段(小时、分钟、秒和毫秒)设置为0,并比较结果时间。与Joda解决方案相比,确实很讨厌:)

时区部分很重要:java.util.Date总是基于UTC。在大多数情况下,我对一个日期感兴趣,那是一个特定时区的日期。这本身将迫使您使用Calendar或Joda Time(除非您想自己考虑时区,我不建议这样做)。

android开发人员的快速参考

//Add joda library dependency to your build.gradle file
dependencies {
     ...
     implementation 'joda-time:joda-time:2.9.9'
}

示例代码(示例)

DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();

Date myDateOne = ...;
Date myDateTwo = ...;

int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);

if(retVal == 0)
   //both dates are equal
else if(retVal < 0)
   //myDateOne is before myDateTwo
else if(retVal > 0)
   //myDateOne is after myDateTwo