如何在没有时间部分的情况下比较两个日期?

问题描述:

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

I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What's the simplest way?

更新:当时Joda Time是一个很好的推荐,使用 java.time 尽可能使用Java 8+中的库。

Update: while Joda Time was a fine recommendation at the time, use the java.time library from Java 8+ instead where possible.

我的偏好是使用 Joda Time 让这非常简单:

My preference is to use Joda Time which makes this incredibly easy:

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

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

return firstDate.compareTo(secondDate);

编辑:如评论中所述,如果您使用 DateTimeComparator.getDateOnlyInstance() 它甚至更简单:)

As noted in comments, if you use DateTimeComparator.getDateOnlyInstance() it's even simpler :)

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

(使用Joda时间是几乎所有询问 java.util.Date 或 java.util.Calendar 。这是一个非常优秀的API。如果你正在做任何事情重要的日期/时间,如果可能,你应该真的使用它。)

("Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date or java.util.Calendar. It's a thoroughly superior API. If you're doing anything significant with dates/times, you should really use it if you possibly can.)

如果你绝对强制使用在内置API中,您应该使用适当的日期并使用适当的时区创建日历的实例。然后,您可以将每个日历中的每个字段从小时,分钟,秒和毫秒中设置为0,并比较结果时间。与Joda解决方案相比绝对icky :)但

If you're absolutely forced to use the built in API, you should create an instance of Calendar with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)

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

The time zone part is important: java.util.Date is always based on UTC. In most cases where I've been interested in a date, that's been a date in a specific time zone. That on its own will force you to use Calendar or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)

Android开发人员的快速参考

Quick reference for android developers

//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