Memra

Formatting & parsing with DateTimeFormatter

◈ 4 cards

Printing dates in human-readable form and parsing strings back into java.time objects.

DateTimeFormatter

The DateTimeFormatter class converts between java.time objects and String. It comes in two flavours:

Predefined ISO constants — quick and unambiguous:

LocalDate d = LocalDate.of(2024, 6, 15);
String iso  = d.format(DateTimeFormatter.ISO_LOCAL_DATE);  // "2024-06-15"

ofPattern(...) for locale-style formatting:

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String text = d.format(fmt);                  // "15/06/2024"
LocalDate back = LocalDate.parse(text, fmt);  // parse it back

Pattern letters (case-sensitive):

SymbolMeaningExample
d / ddday of month5 / 05
M / MM / MMMmonth6 / 06 / Jun
yyyy4-digit year2024
HHhour 0–2314
mmminutes30
ssseconds00

When the input string does not match the pattern, parse throws DateTimeParseException — a RuntimeException. You may catch it if parsing user input.

pattern2024-06-15T14:30 formats asdd/MM/yyyy15/06/2024dd/mm/yyyy15/30/2024yyyy-MM-dd HH:mm2024-06-15 14:30M is month, m is minutes.
Case is the entire difference between the first two rows. The second pattern is perfectly legal — it just prints the minutes where you meant the month, so nothing fails and the output is wrong.
NORMAL ~/memra/learn/java-from-zero/datetimeformatter utf-8 LF