【问题标题】:What is the easiest way to find whether a particular LocalDate falls within a YearMonth?查找特定 LocalDate 是否在 YearMonth 内的最简单方法是什么?
【发布时间】:2017-11-20 20:18:03
【问题描述】:

documentation for YearMonth 没有任何关于如何处理此问题的建议。

目前我正在使用以下方法检查LocalDate 是否属于YearMonth,其中dateyearMonth 分别是它们的值:

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

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

【问题讨论】:

  • 为什么不能简单比较月份值?
  • 因为我没有跳出框框思考?这可能是一种更清晰的方法:不过,我必须比较月份和年份的值!
  • 这让我觉得YearMonth.from(date).equals(yearMonth) 可能是最简单的方法!

标签: java java-time date-comparison localdate


【解决方案1】:

正如@cricket_007 在问题的 cmets 中指出的那样,检查 LocalDate 是否属于 YearMonth 的一种更简洁的方法是获取 dateYearMonth,然后将其与原始值进行比较给yearMonth

return YearMonth.from(date).equals(yearMonth);

【讨论】:

    【解决方案2】:

    更直接的方式

    fun LocalDate.toYearMonth(): YearMonth {
        return YearMonth.of(get(ChronoField.YEAR), get(ChronoField.MONTH_OF_YEAR))
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多