Search code examples
javajava-timedate-comparisonlocaldate

What is the easiest way to find whether a particular LocalDate falls within a YearMonth?


The documentation for YearMonth does not have any advice for how to handle this.

At the moment I'm using the following method to check whether a LocalDate falls within a YearMonth, where date and yearMonth are values for those respectively:

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

Is there any cleaner or in-built way to do this?


Solution

  • As pointed out by @cricket_007 in the question's comments, a cleaner way to check whether a LocalDate falls within the YearMonth is to get the YearMonth of the date and then to compare that to the original to the yearMonth:

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