DateTimeFormatter Overview and Built-In Formatters
You'll learn how DateTimeFormatter converts temporal objects to/from strings and how to use Java's predefined formatters.
What Is DateTimeFormatter?
DateTimeFormatter is the gateway between your LocalDate, LocalTime, LocalDateTime, ZonedDateTime, and other temporal objects and their human-readable string representations. Think of it as a translator that speaks both "computer time" (the structured objects) and "human time" (formatted text like "2024-03-15" or "March 15, 2024").
Unlike the old SimpleDateFormat, DateTimeFormatter is immutable and thread-safe, making it perfect for modern concurrent applications.
Using Built-In Formatters
Java provides ready-made formatters for common patterns. The most useful ones follow ISO-8601 standards:
LocalDate date = LocalDate.of(2024, 3, 15);
LocalDateTime dateTime = LocalDateTime.of(2024, 3, 15, 14, 30);
// ISO_LOCAL_DATE: "2024-03-15"
String isoDate = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
// ISO_LOCAL_DATE_TIME: "2024-03-15T14:30:00"
String isoDateTime = dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
// ISO_DATE: includes zone if present, "2024-03-15"
String genericDate = date.format(DateTimeFormatter.ISO_DATE);
Parsing with Built-In Formatters
The same formatters work in reverse:
LocalDate parsed = LocalDate.parse("2024-03-15", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime parsedDateTime = LocalDateTime.parse("2024-03-15T14:30:00");
// Note: parse() uses ISO_LOCAL_DATE_TIME by default
Other useful built-ins include ISO_LOCAL_TIME, ISO_ZONED_DATE_TIME, ISO_INSTANT, and BASIC_ISO_DATE (without hyphens).
Key Takeaway: DateTimeFormatter converts temporal objects to/from strings; built-in formatters like ISO_LOCAL_DATE and ISO_DATE_TIME handle standard formats without custom configuration, and they're thread-safe unlike legacy date formatters.