0

文档YearMonth没有任何关于如何处理的建议。

目前我正在使用以下方法来检查 a 是否LocalDate属于 a YearMonth, wheredateyearMonthare 分别为这些值:

YearMonth lastDayOfPreviousMonth = yearMonth.atDay(1).minusDay(1);
YearMonth firstDayOfNextMonth = yearMonth.atEndOfMonth().plusDays(1);
return date.isAfter(lastDayOfPreviousMonth)
                && date.isBefore(firstDayOfNextMonth);

有没有更清洁或内置的方法来做到这一点?

4

2 回答 2

9

正如@cricket_007 在问题评论中所指出的那样,检查 a 是否LocalDate属于a 的一种更简洁的方法YearMonth是获取 the YearMonthdate然后将其与原始内容进行比较yearMonth

return YearMonth.from(date).equals(yearMonth);
于 2017-06-18T15:41:24.387 回答
0

更直接的方式

fun LocalDate.toYearMonth(): YearMonth {
    return YearMonth.of(get(ChronoField.YEAR), get(ChronoField.MONTH_OF_YEAR))
}
于 2021-12-11T10:52:01.540 回答