Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TemporalAdjusters: next weekday and month end

Apply calendar rules through LocalDate.with(...). Distinguish next from nextOrSame and find the last day of a month with lastDayOfMonth, without modifying the input date.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

date.with(TemporalAdjusters.next(dayOfWeek))
date.with(TemporalAdjusters.nextOrSame(dayOfWeek))
date.with(TemporalAdjusters.lastDayOfMonth())

TemporalAdjusters provides static factories for TemporalAdjuster objects. Apply a rule through date.with(...) and retain the result: LocalDate is immutable, so the input date remains unchanged.

TemporalAdjusters.next(dayOfWeek) selects the specified weekday strictly after the input date, advancing it by 1–7 days. TemporalAdjusters.nextOrSame(dayOfWeek) includes the input date, advancing by 0–6 days. The DayOfWeek argument must not be null; the result can fall in the next month or year.

TemporalAdjusters.lastDayOfMonth() selects the last day of the input date's month, accounting for leap years. “Month” refers to that date, not the system clock. LocalDate contains neither a time nor a time zone.

The example uses Thursday 2024-02-29: it demonstrates the difference between next and nextOrSame, the end of February in a leap year, and the unchanged input date.

Examples

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

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2024, 2, 29);
        System.out.println(date.with(TemporalAdjusters.next(DayOfWeek.THURSDAY)));
        System.out.println(date.with(TemporalAdjusters.nextOrSame(DayOfWeek.THURSDAY)));
        System.out.println(date.with(TemporalAdjusters.lastDayOfMonth()));
        System.out.println(date);
    }
}

Result

2024-03-07
2024-02-29
2024-02-29
2024-02-29

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources