Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LocalDate.of — create a date from year, month, and day

Build an ISO date from three fields, choose the overload that fits your input, and compare the resulting dates by value rather than by reference.

Version: Java SE 21

Syntax

public static LocalDate of(int year, int month, int dayOfMonth)
public static LocalDate of(int year, Month month, int dayOfMonth)

LocalDate.of is a static factory method on java.time.LocalDate. It takes the year, month, and day of the month in that order. It returns an immutable ISO-8601 calendar date with no time of day or time zone. Unlike LocalDate.now(), it does not read the clock.

The second argument is either an int from 1 (January) to 12 (December) or a java.time.Month enum constant such as Month.JANUARY. The year must be in the inclusive range -999999999 to 999999999. The day must be from 1 to 31 and must exist in the given month and year. An out-of-range field or a nonexistent date such as February 29, 2019 causes a DateTimeException; the factory does not adjust the date. Passing null as the Month causes a NullPointerException.

LocalDate is a value-based class. Two calls for 2020-01-01 give dates that are equal according to equals, but the factory does not promise separate objects. == compares references, not dates. Do not use LocalDate instances for synchronization.

Examples

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.Month;

public class Main {
    public static void main(String[] args) {
        final int year = 2020;
        LocalDate january = LocalDate.of(year, 1, 1);
        LocalDate sameJanuary = LocalDate.of(year, Month.JANUARY, 1);
        LocalDate june = LocalDate.of(year, Month.JUNE, 1);
        LocalDate july = LocalDate.of(year, 7, 1);
        LocalDate previousDecember = LocalDate.of(year - 1, Month.DECEMBER, 31);

        System.out.println(january);
        System.out.println(june);
        System.out.println(july);
        System.out.println(previousDecember);
        System.out.println(january.equals(sameJanuary));

        try {
            LocalDate.of(year - 1, Month.FEBRUARY, 29);
        } catch (DateTimeException e) {
            System.out.println("DateTimeException");
        }
    }
}

Result

2020-01-01
2020-06-01
2020-07-01
2019-12-31
true
DateTimeException

The program prints fixed dates in January, June, and July 2020 and a December date in the previous year, computed as `year - 1`. Both overloads produce the same January date, so `equals` returns `true`. Since 2019 is not a leap year, the catch block prints `DateTimeException`.

Related lessons

  • Java · Lesson 4 · Advanced · Version: 2
  • Java · Lesson 11 · Advanced · Version: 2

Sources