如何按天比较 DateTime?

How to compare DateTime by day?

我想比较两个 DateTime Joda 对象,以确定日期时间是否在同一天。

因此我使用的 DateTimeComparator 配置为仅比较年与日(因此没有时间比较)。

但是下面的测试成功了,尽管它应该会失败。为什么?

@Test
public void validateDayNotEqual() {
    DateTimeComparator.getInstance(DateTimeFieldType.year(), DateTimeFieldType.dayOfWeek())
    DateTime lastTimestamp = DateTime.now().minusDays(1);
    assertTrue(comparator.compare(DateTime.now(), lastTimestamp) == 0);
}

DateTimeComparator 的 javadoc 中:

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

如您所见,真正的问题是您交换了两个参数,lowerLimitupperLimit。由于upperLimit是独占的,但可以省略,所以应该改为:

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

...或者这也可以正常工作(也许更优雅):

    DateTimeComparator comparator = getDateOnlyInstance();

编辑 2:答案包含严重错误,随后已更正。