- The core class for representing dates without time in Java is
java.time.LocalDate. - You'll need to work with the
yearandmonthprovided in the constructor. - The target day of the week is conveniently provided directly as a
java.time.DayOfWeekenum instance in theday()method.
LocalDateobjects are immutable. To find the target meetup date, you typically start with any date within the targetmonthandyearand then apply an "adjuster" to find the correct day.- For example, you could create a
LocalDatefor the 1st of the month:LocalDate.of(year, month, 1). - For "Teenth" calculations, starting from the 13th of the month (
LocalDate.of(year, month, 13)) can be helpful.
- The key to solving this idiomatically is the
java.time.temporal.TemporalAdjustersutility class (note the plural 's'). It provides static methods that returnTemporalAdjusterinstances for common date calculations. - You apply an adjuster to a
LocalDateusing its.with()method:someLocalDate.with(TemporalAdjusters.someAdjuster(...)) - This returns a new
LocalDateinstance with the adjustment applied.
- Look for a method in
TemporalAdjustersthat allows you to find a date based on its ordinal position (1st, 2nd, 3rd, 4th) and itsDayOfWeekwithin the month. - You might need to convert the
MeetupScheduleenum values (FIRST,SECOND, etc.) into the corresponding integer ordinals (1, 2, 3, 4) to use this adjuster.
TemporalAdjustersprovides a specific adjuster to find the last occurrence of a givenDayOfWeekwithin the month.
- "Teenth" days run from the 13th to the 19th of the month.
- Consider starting from the 13th day of the month (
LocalDate.of(year, month, 13)). - Look for an adjuster in
TemporalAdjustersthat finds the next occurrence of the targetDayOfWeek, potentially including the date you're adjusting if it already matches the target day of the week.
- Use the input
schedule(which is aMeetupScheduleenum value) to determine which specificTemporalAdjustermethod to use. Aswitchstatement orif-else ifchain on theschedulevalue is a common approach.