How to get the first and last day of a month
Short answer
withDayOfMonth(1) gives the first day, TemporalAdjusters.lastDayOfMonth() the last one:
void main() {
var date = LocalDate.of(2026, 2, 17);
IO.println(date.withDayOfMonth(1));
IO.println(date.with(TemporalAdjusters.lastDayOfMonth()));
}Output:
2026-02-01
2026-02-28With YearMonth
YearMonth describes a whole month and knows its length:
void main() {
var month = YearMonth.of(2028, 2);
IO.println(month.atDay(1));
IO.println(month.atEndOfMonth());
IO.println(month.lengthOfMonth());
}Output:
2028-02-01
2028-02-29
29All days of a month
datesUntil() returns a stream of dates:
void main() {
var month = YearMonth.of(2026, 3);
long weekends = month.atDay(1).datesUntil(month.atEndOfMonth().plusDays(1))
.filter(d -> d.getDayOfWeek().getValue() >= 6)
.count();
IO.println(weekends);
}Output:
9Common mistake
Assuming a month always has 30 or 31 days. Setting the day by hand is risky — February may not have that day:
void main() {
LocalDate.of(2026, 2, 30);
}Output:
Exception in thread "main" java.time.DateTimeException: Invalid date 'FEBRUARY 30'Functions used in this recipe
- LocalDate.of() — Creates a date from a year, month and day.