35

我想比较两个日期,但是我遇到了麻烦。一个日期是从一个java.util.date对象创建的,另一个是手动制作的。以下代码是一个示例:

Date ds = new Date();
DateTime d = new DateTime(ds);

DateTime e = new DateTime(2012,12,07, 0, 0);
System.out.println(d.isEqual(e));

然而,测试结果false。我猜是因为时间的缘故。如何检查这两个日期是否彼此相等(我的意思是年、月、日相同)?

4

9 回答 9

55
System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));

或者

System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
于 2012-12-07T13:35:22.747 回答
23

您应该使用toLocalDate()

date1.toLocalDate().isEqual(date2.toLocalDate())

这将摆脱 DateTime 的 Time 部分。

还有另一种方法,但它没有考虑两个日期具有不同时区的情况,因此不太可靠:

date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay())
于 2014-02-04T13:08:21.610 回答
7
return DateTimeComparator.getDateOnlyInstance().compare(first, second);

通过如何比较没有时间部分的两个日期?

于 2015-05-20T19:32:30.547 回答
3

如果您想忽略时间组件(即您只想比较日期),您可以使用 DateMidnight 类而不是 Date Time。因此,您的示例将如下所示:

Date ds = new Date();
DateMidnight d = new DateMidnight(ds);

DateMidnight e = new DateMidnight(2012, 12, 7);
System.out.println(d.isEqual(e));

但请注意,它只会在今天打印“true”:)

另请注意,默认情况下,JDK Date 和所有 Joda-Time 即时类(包括 DateTime 和 DateMidnight)都是使用默认时区构造的。因此,如果您创建一个日期以在代码中进行比较,但从数据库中检索另一个日期,该日期可能以 UTC 存储日期,假设您不在 UTC 时区,您可能会遇到不一致。

于 2012-12-07T17:29:04.867 回答
1

由于它们是 DateTime 对象,因此在比较它们时也会考虑它们的时间部分。尝试将第一个日期的时间部分设置为 0,例如:

d = d.withTime(0, 0, 0, 0);
于 2012-12-07T13:34:19.207 回答
1

我在寻找与今天的比较时偶然发现了这个问题。以下是您可以将日期与今天进行比较的方法:

date1.toLocalDate().isBeforeNow() // works also with isAfterNow
于 2018-08-09T15:09:19.193 回答
0

这是一种对我有用的静态方法。

public static boolean isSameDay(DateTime date1, DateTime date2){
    return date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay());
}
于 2017-10-21T09:56:10.910 回答
-1
DateTimeComparator.getDateOnlyInstance().compare(obj1, obj2);

obj1 和 obj2 可以是 String、Long、Date(java.util)... 详情见 http://www.joda.org/joda-time/apidocs/index.html?org/joda/time/DateTimeComparator .html

于 2018-01-07T13:45:50.207 回答
-5

编写自己的方法

public boolean checkEqual(DateTime first,DateTime second){
     if(first.<getterforyear> == second.<getterforyear> && first.<getterformonth> == second.<getterformonth> && first.<getterforday> == second.<getterforday>){
         return true;
  }
 return false;
}
于 2012-12-07T13:40:56.367 回答