In Java, withDayOfMonth(dayOfMonth) returns a new LocalDateTime with the day of the month set to the value you pass. The year, the month, and the time of day are copied from the original.
LocalDateTime is immutable, so the original object never changes. Always keep the result: dt = dt.withDayOfMonth(1);. It is a quick way to jump to the first of the month, or to a fixed billing or payment day.
An instance method of java.time.LocalDateTime (since Java 8): call it on a LocalDateTime object. Add import java.time.LocalDateTime; at the top of your file.
Syntax
Call it on a LocalDateTime and pass the new day of the month.
invoice: 2026-03-15T08:00
due: 2026-03-28T08:00
next due: 2026-04-28T08:00
How It Works
An invoice. It is created on 15 March 2026 at 08:00.
Set the 28th.withDayOfMonth(28) gives 28 March, with the time kept.
Next month first.plusMonths(1) moves to April, and then withDayOfMonth(28) picks the 28th there.
Why 28? Every month has a 28th, so this call can never throw.
Frequently Asked Questions
Call dt.withDayOfMonth(value). It returns a new LocalDateTime with that part replaced and everything else copied.
No. LocalDateTime is immutable, so withDayOfMonth() returns a new object and leaves the original as it was.
A day that does not exist in that month, such as 31 in April or 29 in February of a normal year, throws a DateTimeException. Days below 1 or above 31 always fail.
Call dt.withDayOfMonth(1). It keeps the time, so use toLocalDate() or truncatedTo(ChronoUnit.DAYS) if you want midnight.
Use dt.with(TemporalAdjusters.lastDayOfMonth()). That works for every month and leap year without checking the length yourself.