All 15 Java Date & Time API (java.time) questions
More in Java Date & Time API (java.time)
Advertisement
Back to results for “Date”
Java › Java Date & Time API (java.time)

What is the difference between LocalDate, LocalTime, LocalDateTime, and ZonedDateTime, and when would you use each?

Intermediate

Answer

LocalDate represents a date without any time-of-day or timezone component (like a birthday, January 15); LocalTime represents a time-of-day without any date or timezone (like 'every day at 9:00 AM'); LocalDateTime combines both a date and time but STILL has no timezone information attached, representing a date-time as observed in some unspecified, implicit location; ZonedDateTime adds explicit timezone information to a date-time, correctly representing a genuine, unambiguous point in time across the globe -- choosing the right one depends on whether your data genuinely needs a timezone (anything crossing time zones, like scheduling a meeting across offices, needs ZonedDateTime; local, timezone-independent concepts like a birthday or a recurring daily local event fit LocalDate/LocalTime/LocalDateTime).
LocalDate birthday = LocalDate.of(1990, 5, 15);              // just a date, no time or zone
LocalTime lunchTime = LocalTime.of(12, 30);                    // just a time, no date or zone
LocalDateTime meeting = LocalDateTime.of(2024, 6, 1, 14, 0);    // date+time, but no zone -- ambiguous globally
ZonedDateTime flight = ZonedDateTime.of(meeting, ZoneId.of("America/New_York"));  // fully unambiguous
Real-world example A flight booking system stores departure times as ZonedDateTime (since a flight's exact moment in universal time genuinely matters and must be unambiguous across timezones), while a user's stored birthday uses LocalDate (since a birthday is a timezone-independent, purely calendrical concept that shouldn't shift depending on where the user happens to be).

Common follow-ups: Why is LocalDateTime specifically dangerous to use for representing a genuine, globally-unambiguous instant in time?;How does Instant differ from all four of these types, and when would you use it instead?