Video in progress
What is the difference between Instant, LocalDateTime, ZonedDateTime and OffsetDateTime in java.time, and when do you use each?
Example / When — Instant: 2026-11-01T09:00:00Z / logs, audit, "when did it happen"; LocalDate: 2026-11-01 / a birthday, a holiday; LocalDateTime: 2026-11-01T14:00 / "class every day at 14:00" (a plan with no time zone); ZonedDateTime: ...T14:00+05:00[Asia/Tashkent] / showing to the user, calculating with zone rules…
📖 Answer
| Type | Example | When |
|---|---|---|
Instant |
2026-11-01T09:00:00Z |
logs, audit, "when did it happen" |
LocalDate |
2026-11-01 |
a birthday, a holiday |
LocalDateTime |
2026-11-01T14:00 |
"class every day at 14:00" (a plan with no time zone) |
ZonedDateTime |
...T14:00+05:00[Asia/Tashkent] |
showing to the user, calculating with zone rules |
OffsetDateTime |
...T14:00+05:00 |
exchanging with APIs and the database (timestamptz) |
Common mistakes:
- storing the time of an event as a
LocalDateTime: if the server moves to another zone, or two servers are in different zones, the times get mixed up; LocalDateTime.now()depends on the server's zone;- doing date arithmetic with
Instant: "next month" doesn't exist inInstant, for that you needZonedDateTimeorLocalDate; - untestable code: calling
now()everywhere. Inject aClockand give itClock.fixed(...)in tests.
Instant now = Instant.now(clock);
ZonedDateTime tashkent = now.atZone(ZoneId.of("Asia/Tashkent"));
String shown = tashkent.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"));
java.util.Date and Calendar are mutable and awkward: don't use them in new code.
Sign up to mark studied questions and save your progress.