โ Java Time Handling Guide
Master Java's modern time API (java.time) and avoid the pitfalls of legacy Date/Calendar classes.
โก Quick Reference
โ Use (Java 8+)
- โข Instant for UTC timestamps
- โข ZonedDateTime for timezone-aware times
- โข OffsetDateTime for API serialization
- โข LocalDateTime only for timezone-naive data
- โข DateTimeFormatter for parsing/formatting
โ Avoid (Legacy)
- โข java.util.Date (mutable, timezone-naive)
- โข java.util.Calendar (complex, error-prone)
- โข SimpleDateFormat (not thread-safe)
- โข Timestamp arithmetic without timezone
- โข Hardcoded timezone offsets
๐ Modern Time API (java.time)
Core Classes and When to Use Them
๐ Timezone Handling
ZonedDateTime vs OffsetDateTime
๐ Parsing and Formatting
Thread-Safe Date Parsing
โฑ๏ธ Duration and Period
Time-Based vs Date-Based Calculations
๐๏ธ Database Integration
JPA and JDBC with Modern Time API
๐งช Testing Time Logic
Clock Abstraction for Testing
๐ Migration from Legacy APIs
Converting from Date/Calendar
โ ๏ธ Common Pitfalls
Things That Will Bite You
1. LocalDateTime Timezone Confusion
LocalDateTime has no timezone - don't use it for timestamps!
2. Instant vs ZonedDateTime Confusion
Know when to use each for different scenarios.