Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

DateTimeFormatter — formatting and parsing dates

DateTimeFormatter converts dates and times to text and parses text. Learn patterns, explicit Locale selection, strict validation, and the distinctions MM versus mm and uuuu versus yyyy.

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

Syntax

DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm").withLocale(Locale.ROOT).withResolverStyle(ResolverStyle.STRICT)

DateTimeFormatter is immutable and thread-safe. DateTimeFormatter.ofPattern creates a formatter from a pattern; reuse it for formatting and parsing.

For MM versus mm: MM means a two-digit month, whereas mm means two-digit minutes. For uuuu versus yyyy: uuuu means the proleptic year, whereas yyyy means year-of-era. For strict ISO date parsing without an era, use uuuu; yyyy alone cannot resolve the date.

DateTimeFormatter.withLocale returns a formatter with the selected Locale, affecting features such as month names. DateTimeFormatter.withResolverStyle also leaves the original unchanged. Choose ResolverStyle.STRICT to reject invalid dates. The default for ofPattern, SMART, can adjust the day to the month's end, for example 2023-02-29 to 2023-02-28.

The example accepts 2024-02-29 09:07 but rejects 2023-02-29 09:07. STRICT controls field resolution during parsing, not formatting.

Examples

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("uuuu-MM-dd HH:mm")
                .withLocale(Locale.ROOT)
                .withResolverStyle(ResolverStyle.STRICT);

        LocalDateTime value = LocalDateTime.parse("2024-02-29 09:07", formatter);
        System.out.println(value.format(formatter));

        try {
            LocalDateTime.parse("2023-02-29 09:07", formatter);
            throw new AssertionError("Expected rejection");
        } catch (DateTimeParseException ex) {
            System.out.println("Invalid date rejected");
        }
    }
}

Result

2024-02-29 09:07
Invalid date rejected

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