Date & Time API
Date/Time Formatting
Format and parse date-time objects using the thread-safe DateTimeFormatter.
Interview: Commonly tested on DateTimeFormatter thread safety, custom pattern syntax, and parsing strings.
The java.time.format.DateTimeFormatter class is the modern, thread-safe replacement for SimpleDateFormat. It is used to format and parse date-time objects.
Core Idea
DateTimeFormatter instances are completely immutable and thread-safe. They can be shared globally.
Why It Matters
Allows declaring formatter constants static final without synchronization or thread-local wrappers.
Interview Lens
Tests formatter pattern syntax (e.g. yyyy vs uuuu) and handling parse exceptions.
Formatting and Parsing
- Formatting: Convert a date-time object to a string:
formatter.format(date). - Parsing: Convert a string to a date-time object:
LocalDate.parse(text, formatter). - Standard Formats:
DateTimeFormatter.ISO_LOCAL_DATEprovides preconfigured ISO-8601 formatting.
Code Walkthrough
This program demonstrates using DateTimeFormatter to format dates and parse custom string inputs.
Interview-Relevant Information
Q: Why is DateTimeFormatter thread-safe while SimpleDateFormat is not?
Answer: SimpleDateFormat maintains mutable state fields (like calendar allocations) that are updated during parsing and formatting. If multiple threads call it, they corrupt each other's state. DateTimeFormatter is completely immutable and stateless: it creates temporary evaluator objects on the stack for each method invocation, guaranteeing thread-safety.
Quick Checklist
Can DateTimeFormatter be declared static final safely? How do you handle custom date patterns? If yes, you understand modern date-time formatting.
Use Cases
Parsing user string inputs into LocalDate models.
Formatting system timestamps for log metrics.
Common Mistakes
Using lowercase 'yyyy' for week-based-year formatting under certain locales (use 'uuuu' or capital 'YYYY' carefully based on local rules).
Not catching DateTimeParseException when parsing unvalidated user input strings.