Memra

Formatting & parsing with DateTimeFormatter

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):

| Symbol | Meaning | Example | |---|---|---| | d / dd | day of month | 5 / 05 | | M / MM / MMM | month | 6 / 06 / Jun | | yyyy | 4-digit year | 2024 | | HH | hour 0–23 | 14 | | mm | minutes | 30 | | ss | seconds | 00 |

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

NORMAL ~/memra/learn/java-from-zero/datetimeformatter utf-8 LF