membersound membersound - 1 year ago 82
Java Question

How to compare DateTime by day?

I want to compare two

Joda objects, to find out if the datetime is on the same day or not.

Therefore I'm using a
configured to compare from year to day only (so no time comparison).

But the following test succeeds, even though it should fail. Why?

public void validateDayNotEqual() {
DateTimeComparator.getInstance(DateTimeFieldType.year(), DateTimeFieldType.dayOfWeek())
DateTime lastTimestamp =;
assertTrue(, lastTimestamp) == 0);

Answer Source

In the javadoc of DateTimeComparator:

public static DateTimeComparator getInstance(DateTimeFieldType lowerLimit,
                                             DateTimeFieldType upperLimit)
Returns a DateTimeComparator with a lower and upper limit. Fields of a magnitude less than the lower limit are excluded from comparisons. Fields of a magnitude greater than or equal to the upper limit are also excluded from comparisons. Either limit may be specified as null, which indicates an unbounded limit.

    lowerLimit - inclusive lower limit for fields to be compared, null means no limit
    upperLimit - exclusive upper limit for fields to be compared, null means no limit

    a comparator over all fields between the limits

As you can see, the real problem was that you swapped the two arguments, the lowerLimit and the upperLimit. Since the upperLimit is exclusive but it can be omitted, it should be changed to:

    DateTimeComparator comparator = DateTimeComparator.getInstance(DateTimeFieldType.dayOfMonth());

...or this would also work fine (and perhaps more elegant):

    DateTimeComparator comparator = getDateOnlyInstance();

EDIT 2: The answer had contained serious errors and were subsequently corrected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download