Get Last Day of Next Month Using Java's Time API

Java 8 introduces the concept of TemporalAdjusters. These are essentially time adjusters. You can read more about these here.

In order to get the last date of the next month, we first find the current date, and then we adjust the date using the strategy we need here - which is first an adjuster for the first day of the next month, and then an adjuster for the last day of the adjusted month.

In the Java Time API method naming convention, with returns a copy of the target object with one element changed. In the following example, the day of month is changed.


import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

public final class DateUtility {

    private DateUtility() {}
    
    public static LocalDate getLastOfNextMonth() {
        return LocalDate.now()
                .with(TemporalAdjusters.firstDayOfNextMonth())
                .with(TemporalAdjusters.lastDayOfMonth());
    }

}