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:40

This is a static method which works for me.

public static boolean isSameDay(DateTime date1, DateTime date2){
    return date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay());
}
查看更多
We Are One
3楼-- · 2019-01-23 02:46

You should use toLocalDate():

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

This will get rid of the Time part of the DateTime.

There is another approach, but it does not account for the case where the two dates have a different timezone, so it's less reliable:

date1.withTimeAtStartOfDay().isEqual(date2.withTimeAtStartOfDay())
查看更多
叼着烟拽天下
4楼-- · 2019-01-23 02:46
return DateTimeComparator.getDateOnlyInstance().compare(first, second);

Via How to compare two Dates without the time portion?

查看更多
登录 后发表回答