Java - Date & Time (java.time)
Date & Time (java.time)
Key Types
- LocalDate, LocalTime, LocalDateTime — no zone
- ZonedDateTime, OffsetDateTime — with zone/offset
- Instant — machine timestamp (UTC)
- Duration/Period — amount of time (time-based vs date-based)
Examples
import java.time.*;
LocalDate d = LocalDate.now();
LocalDateTime dt = LocalDateTime.now();
ZonedDateTime z = ZonedDateTime.now(ZoneId.of("UTC"));
Duration dur = Duration.between(Instant.now(), Instant.now().plusSeconds(5));
Period p = Period.between(LocalDate.of(2020,1,1), LocalDate.now());
Formatting and Parsing
import java.time.format.DateTimeFormatter;
String s = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(z);
LocalDate parsed = LocalDate.parse("2024-10-15");
Time Zones
Always store in UTC (Instant) and convert to user-facing zones at the edges.
Architect note: Avoid legacy java.util.Date/Calendar in new code. Use java.time exclusively.
Try it
- Parse a date string into
LocalDate
and format it in another style. - Convert a
ZonedDateTime
from your local zone to UTC and print both.