Date & Time API
New Date/Time API
Overview of the JSR-310 java.time framework introduced in Java 8.
Interview: Focuses on core JSR-310 design principles: immutability, thread safety, clear separation of concerns, and timezone handling.
Java 8 introduced the java.time package (JSR-310). This API is completely immutable, thread-safe, and designed with a clear separation of concerns.
Core Idea
JSR-310 structures are immutable. All modifications return a new class instance, ensuring thread safety.
Why It Matters
Eliminates synchronization overhead and prevents race conditions during date formatting and calculations.
Interview Lens
Expect design questions comparing old mutable calendar configurations with the new immutable architecture.
Core JSR-310 Classes
LocalDate: Represents a date without a timezone (YYYY-MM-DD).LocalTime: Represents a time without a timezone (HH:mm:ss).LocalDateTime: Combines LocalDate and LocalTime.ZonedDateTime: Represents a date and time with a specific timezone (e.g. UTC, Europe/Paris).Instant: Represents a specific moment in time on the timeline (GMT epoch timeline). Used for logging timestamps.
Code Walkthrough
This program demonstrates the immutability of the new date-time classes.
Interview-Relevant Information
Q: How does the new API handle timezone transitions (like Daylight Saving Time)?
Answer: Classes like ZonedDateTime resolve DST boundaries automatically using the underlying timezone database. If you add time across a transition limit, the timezone offset adjusts automatically to maintain correct local calculations.
Quick Checklist
What package stores modern date classes? Are java.time classes thread-safe? If yes, you understand the new Date-Time API.
Use Cases
Representing timezone-insensitive database records (e.g. birth dates).
Calculating precise execution durations in concurrent applications.
Common Mistakes
Expecting methods like plusDays() to modify the calling object instead of capturing the returned new instance.
Using LocalDateTime when timezone context is required (use ZonedDateTime or OffsetDateTime instead).