All 15 Java Date & Time API (java.time) questions
More in Java Date & Time API (java.time)
Advertisement
Java › Java Date & Time API (java.time)

How do you parse and format date/time values using DateTimeFormatter, and how does this replace the older, notoriously thread-unsafe SimpleDateFormat class?

Intermediate

Answer

DateTimeFormatter (immutable and thread-safe, unlike the older SimpleDateFormat which was famously NOT thread-safe and required careful per-thread instance management or external synchronization to use safely in concurrent code) provides both predefined standard formatters (ISO_LOCAL_DATE, ISO_DATE_TIME) and a pattern-based custom formatter (via ofPattern(), using largely similar pattern letters to SimpleDateFormat's own pattern syntax) for both parsing a String into a date/time object and formatting a date/time object into a String, with a single DateTimeFormatter instance safely shareable and reusable across multiple threads simultaneously, unlike SimpleDateFormat which required a new instance per use (or ThreadLocal-based pooling) to avoid subtle, hard-to-diagnose concurrency bugs.
// Modern, thread-safe DateTimeFormatter -- safe to share as a static final constant across threads
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime dateTime = LocalDateTime.parse("2024-06-01 14:30:00", FORMATTER);
String formatted = dateTime.format(FORMATTER);

// vs. the OLD, unsafe-to-share SimpleDateFormat, which required per-use or per-thread instances
// SimpleDateFormat oldFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  // NOT safe as a shared static field!
Real-world example A team migrating from SimpleDateFormat to DateTimeFormatter fixes a subtle, intermittent production bug where dates were occasionally parsed incorrectly under concurrent load, traced directly to a shared static SimpleDateFormat instance being used unsafely across multiple threads simultaneously, a bug class entirely eliminated by DateTimeFormatter's inherent thread safety.

Common follow-ups: What specific internal mutable state made SimpleDateFormat unsafe for concurrent use in the first place?;How do DateTimeFormatter's predefined ISO formatters differ from a custom ofPattern()-based formatter in terms of strictness and flexibility?