Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LocalDate: create, shift, compare, and display dates

Create an ISO calendar date, shift it by calendar days without changing the original, check whether one date is later than another, and turn a date into text.

Version: Java SE 21

Syntax

import java.time.LocalDate;
import java.time.Month;
import java.time.chrono.ChronoLocalDate;

// Method signatures on LocalDate (Java SE 21)
public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate of(int year, Month month, int dayOfMonth)
public LocalDate plusDays(long daysToAdd)
public boolean isAfter(ChronoLocalDate other)
public String toString()

java.time.LocalDate represents an ISO calendar date without a time of day or time zone. The static factory LocalDate.of takes the year, month, and day of the month in that order. Pass the month as an int from 1 to 12 or as a non-null Month value such as Month.FEBRUARY. An invalid date, such as February 29 in a non-leap year, throws DateTimeException rather than being adjusted.

date.plusDays(n) takes a long number of calendar days and returns the resulting date, crossing month or year boundaries as needed. A negative value moves backward; zero leaves the date value unchanged. LocalDate is immutable: the call does not change date, so store or use the returned value. If the calculation does not overflow but the resulting date is outside the supported range, the method throws DateTimeException, as in LocalDate.MAX.plusDays(1). In JDK 21, if the intermediate addition to the epoch-day value overflows a long, the method throws ArithmeticException before checking the date range.

a.isAfter(b) returns true only when a is later than b. It returns false when a is earlier or both represent the same day. The parameter type is ChronoLocalDate, and b must not be null. The comparison uses the dates' positions on the local timeline, ignoring their calendar systems.

date.toString() returns a String in ISO-8601 uuuu-MM-dd form, such as 2024-03-01. It does not print anything or adapt the text to a locale. For a reader-facing format, use format with a suitable DateTimeFormatter.

Examples

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2024, 2, 28);
        LocalDate later = start.plusDays(2);

        System.out.println(start.toString());
        System.out.println(later.toString());
        System.out.println(later.isAfter(start));
        System.out.println(later.isAfter(later));
    }
}

Result

2024-02-28
2024-03-01
true
false

2024 is a leap year, so two days after `2024-02-28` is `2024-03-01`. The first line shows the original date is unchanged; the last two show that the result is after the original date but not after itself.

Related lessons

  • Java · Lesson 68 · Basic · Version: 2

Sources