Comparing two dates using Joda time

2019-01-23 01:42发布

I want to compare two dates, however I'm running into trouble. 1 date is created from a java.util.date object and the other is manually crafted. The following code is an example:

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

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

However the test turns out false. I am guessing that it is because of the time. How can I check if these two dates are equal to each other (I mean the Year, month, date are identical)?

9条回答
成全新的幸福
2楼-- · 2019-01-23 02:19

Write your own method

public boolean checkEqual(DateTime first,DateTime second){
     if(first.<getterforyear> == second.<getterforyear> && first.<getterformonth> == second.<getterformonth> && first.<getterforday> == second.<getterforday>){
         return true;
  }
 return false;
}
查看更多
Viruses.
3楼-- · 2019-01-23 02:20
DateTimeComparator.getDateOnlyInstance().compare(obj1, obj2);

obj1 and obj2 can be a String, Long, Date(java.util)... For the details see http://www.joda.org/joda-time/apidocs/index.html?org/joda/time/DateTimeComparator.html

查看更多
家丑人穷心不美
4楼-- · 2019-01-23 02:29

If you want to ignore time components (i.e. you want to compare only dates) you can use DateMidnight class instead of Date Time. So your example will look something like this:

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

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

But beware, it will print "true" only today :)

Also note that by default JDK Date and all Joda-Time instant classes (DateTime and DateMidnight included) are constructed using default timezone. So if you create one date to compare in code, but retrieve another one from the DB which probably stores dates in UTC you may encounter inconsistencies assuming you are not in UTC time zone.

查看更多
beautiful°
5楼-- · 2019-01-23 02:33

As they're DateTime objects, their time parts are also taken into consideration when you're comparing them. Try setting the time parts of the first date to 0, like:

d = d.withTime(0, 0, 0, 0);
查看更多
男人必须洒脱
6楼-- · 2019-01-23 02:35
System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));

or

System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-23 02:39

I stumbled into this question while looking for a comparison with today. Here's how you can compare a date to today :

date1.toLocalDate().isBeforeNow() // works also with isAfterNow
查看更多
登录 后发表回答