Find First and Last Day of a Month in Java
Problem
A TemporalAdjuster moves a date to a related date, such as the start or end of its month, applying all calendar rules for you.
Given any date, find the first and last day of its month, their weekdays, and how many days the month has.
Java Program
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
public class FirstLastDayOfMonth {
public static void main(String[] args) {
LocalDate any = LocalDate.of(2028, 2, 14);
LocalDate first = any.with(TemporalAdjusters.firstDayOfMonth());
LocalDate last = any.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("First day: " + first + " (" + first.getDayOfWeek() + ")");
System.out.println("Last day: " + last + " (" + last.getDayOfWeek() + ")");
YearMonth ym = YearMonth.from(any);
System.out.println("Days in " + ym + ": " + ym.lengthOfMonth() + " (leap year: " + ym.isLeapYear() + ")");
}
}Output
Core Logic
with(TemporalAdjusters...) jumps to the boundary of the month, and YearMonth describes the month itself.
- 1
any.with(firstDayOfMonth())returns the 1st of the same month. - 2
any.with(lastDayOfMonth())returns the correct last day — 28, 29, 30 or 31. - 3
YearMonth.from(any)reports the month's length and whether its year is a leap year.
Key Point: Never hard-code month lengths; February and leap years are exactly where hand-written tables go wrong.
Key Concepts
Approach 2: First and Last Weekdays
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class FirstLastWeekdayOfMonth {
public static void main(String[] args) {
LocalDate any = LocalDate.of(2026, 5, 20);
LocalDate firstMonday = any.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
LocalDate lastFriday = any.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
LocalDate secondTuesday = any.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.TUESDAY));
System.out.println("First Monday of May 2026: " + firstMonday);
System.out.println("Last Friday of May 2026: " + lastFriday);
System.out.println("Second Tuesday of May 2026: " + secondTuesday);
}
}
Output
Core Logic
Other adjusters find a particular weekday within the month, which is how "first Monday" or "last Friday" rules are written.
- 1
firstInMonth(DayOfWeek.MONDAY)finds the first Monday. - 2
lastInMonth(DayOfWeek.FRIDAY)finds the last Friday. - 3
dayOfWeekInMonth(2, DayOfWeek.TUESDAY)finds the second Tuesday.
Key Point: These adjusters express scheduling rules such as "payday is the last Friday" in one call.
Key Concepts
Interview Questions
How do you get the last day of the previous month?
date.withDayOfMonth(1).minusDays(1), or date.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).
How do you check whether a date is the last day of its month?
Compare date.getDayOfMonth() with date.lengthOfMonth().