Java 8 Time API:将YearMonth与LocalDate进行比较?

时间:2017-05-05 09:01:08

标签: java java-8 java-time

是否有一种方便的方法可以将YearMonth与Java 8时间API中的LocalDate(或任何其他时间)进行比较?

我想知道如此多的方法支持TemporalAccessors,我是否只是看错了地方,确实存在这样一种方便的方法。任何提示都受到高度赞赏。

要使问题更清晰:如果我将YearMonthLocalDate进行比较,我只对monthyear(两者的共同标准)的比较感兴趣。

2 个答案:

答案 0 :(得分:1)

YearMonth和LocalDate不能直接比较,因为LocalDate持有未在yearMont类中定义的天数。

你可以写自己的

private boolean checkTemporal(YearMonth yM, LocalDate lD) {

    return yM.getMonthValue() == lD.getMonthValue() && yM.getYear() == lD.getYear();
}

答案 1 :(得分:0)

将一个时间包裹到比较所需的公分母类型中似乎相当方便,例如为了将YearMonthLocalDate进行比较,LocalDate首先转换为YearMonth

LocalDate someDate = ...
YearMonth someMonth = ...

YearMonth.from(someDate).equals(someMonth)

// or compareTo if required

更多地考虑它,可能没有通用compare - 方法,因为比较保持特定。无法保证有人只想比较两者的共同点。