Reputation: 86777
I want to compare two DateTime
Joda objects, to find out if the datetime is on the same day or not.
Therefore I'm using a DateTimeComparator
configured to compare from year to day only (so no time comparison).
But the following test succeeds, even though it should fail. Why?
@Test
public void validateDayNotEqual() {
DateTimeComparator.getInstance(DateTimeFieldType.year(), DateTimeFieldType.dayOfWeek())
DateTime lastTimestamp = DateTime.now().minusDays(1);
assertTrue(comparator.compare(DateTime.now(), lastTimestamp) == 0);
}
Upvotes: 0
Views: 189
Reputation: 696
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.
Parameters:
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
Returns:
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.
Upvotes: 4