How do I format a date using DateTimeFormatter in Java?

Use DateTimeFormatter to turn a LocalDate into text. You can choose the order of the day, month, and year, and use a locale to control the language of the month name.

In this example, you will format the same date in two ways: 11/11/2026 and 11 November 2026.

Source code

Save the following code as DateFormattingExample.java:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateFormattingExample {
    void main() {
        LocalDate date = LocalDate.of(2026, 11, 11);

        DateTimeFormatter numericFormat =
                DateTimeFormatter.ofPattern("dd/MM/uuuu");
        DateTimeFormatter longFormat =
                DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.ENGLISH);

        IO.println("Numeric date: " + date.format(numericFormat));
        IO.println("Date with month name: " + date.format(longFormat));
    }
}

Explanation

LocalDate.of(2026, 11, 11) creates a date using the year, month, and day in that order. A LocalDate stores a calendar date without a time or time zone.

The ofPattern() method creates a formatter from a pattern. The letters are case-sensitive:

Pattern Meaning Example
d Day of the month without zero padding 5
dd Day of the month padded to two digits 05
MM Month number padded to two digits 03
MMMM Full month name March
uuuu Calendar year, padded to at least four digits 2026

Slashes and spaces in these patterns appear as written. Locale.ENGLISH makes the full month name appear in English regardless of the system’s default locale.

The date.format(...) call returns a string. You can format the same date in multiple ways because formatting leaves the LocalDate unchanged.

Use uuuu for the calendar year in these patterns. Uppercase YYYY means the week-based year, which can differ from the calendar year near the start or end of a year.

Run the example

Compile and run the file:

javac DateFormattingExample.java
java DateFormattingExample

Output

Numeric date: 11/11/2026
Date with month name: 11 November 2026

To see the difference between d and dd, change the date to LocalDate.of(2026, 3, 5). The numeric format displays 05/03/2026, and the format with the month name displays 5 March 2026.

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.