Search code examples
javalocaldatejava-time

Birthdays in the scope of java.time.LocalDate


I'm trying to select birthdays (independent of the year) within a Collection of java.time.LocalDate . Why LocalDate ? because this type seems the best for birthday.

Let's say I want to filter the birthdays between March 6 and April 30 irrespective of the year. How to do this ?

If I were to do it, I would replace the year in LocalDate and use the method isAfter and isBefore. The fact that I have to change the year is just a plain hack. Or I used the wrong data type (LocalDate)


Solution

  • I would rather use the type MonthDay which is the "date-without-year" and which is also comparable and offers methods like isAfter() or isBefore(). Furthermore, a MonthDay can be extended to a LocalDate using the method atYear(int).

    If you insist on LocalDate then you should only use leap years because otherwise the 29th of February would be a problem.