CodeBlanks Logo Icon CodeBlanks

DateTimeFormatter

Learn formatting with DateTimeFormatter.

Formatting with DateTimeFormatter

DateTimeFormatter turns dates and times into strings and reads them back. You create one with ofPattern by giving a pattern.

Example: DateTimeFormatter f = DateTimeFormatter.ofPattern("dd.MM.yyyy"). Then date.format(f) writes the date as "15.01.2024". The letters in the pattern have fixed meaning: dd day, MM month, yyyy year. To parse back, use LocalDate.parse(string, f).

format and parse

The format method turns a date into a string; parse turns a string into a date. Both take a DateTimeFormatter as a parameter.

Example: String s = date.format(f) and LocalDate d = LocalDate.parse("15.01.2024", f). The pattern must match the shape of the string; otherwise a DateTimeParseException is thrown. When reading user-entered dates it is always safe to use an explicit formatter.

Practice Format a date with dd.MM.yyyy

Create a date with LocalDate.of(2024, 1, 15). Build a formatter with DateTimeFormatter.ofPattern("dd.MM.yyyy"). Turn the date into a string with format and print it with System.out.println.

Starter code

Main.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

// Create Jan 15 2024 with LocalDate.of
// Build a dd.MM.yyyy formatter with ofPattern
// Format and print the result

Sample solution

Main.java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class FormatDate {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2024, 1, 15);
        DateTimeFormatter f = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        System.out.println(date.format(f));
    }
}

Expected output

15.01.2024

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the ofPattern call

Question
DateTimeFormatter f = DateTimeFormatter.____("dd.MM.yyyy");
Answer
DateTimeFormatter f = DateTimeFormatter.ofPattern("dd.MM.yyyy");

Explanation: ofPattern creates a formatter from a pattern.

2 Match the DateTimeFormatter methods

Term Meaning
ofPattern Creates from pattern
format Turns into string
parse Reads from string
dd.MM.yyyy Pattern

3 Which method turns a LocalDate into a string?

  • of
  • format Correct answer
  • now
  • parse

Explanation: format turns a date into a string with a formatter.

All lessons in Advanced