โ˜• 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.