Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LocalDate from YearMonth with nth DayOfWeek

I would like to convert a YearMonth to a LocalDate with the specified DayOfWeek, e.g. the second Tuesday of February 2019.

The following code throws a DateTimeException:

YearMonth yearMonth = YearMonth.of(2019, Month.FEBRUARY);
TemporalAdjuster secondTuesday = TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY);

LocalDate date = LocalDate.from(yearMonth).with(secondTuesday);

In order to make my code work I need to replace the last line with

LocalDate date = yearMonth.atDay(1).with(secondTuesday);

Isn't there a cleaner solution that doesn't require the use of atDay(1)?

like image 440
jippiee Avatar asked Nov 04 '25 17:11

jippiee


1 Answers

You have found the best and cleanest (or the least poor) solution yourself already:

LocalDate date = yearMonth.atDay(1).with(secondTuesday);

The argument to atDay doesn’t necessarily need to be 1, but it needs to be a valid day of the month in question, so why not 1?

with() always returns the same type you called it on. That is, YearMonth.with() will always return a YearMonth, never a LocalDate. Therefore you cannot use your adjuster there.

I understand and share your objection, but what you’ve got already is the best we can do. You can and should probably wrap it inside a method with a nice name.

like image 183
Ole V.V. Avatar answered Nov 06 '25 10:11

Ole V.V.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!