← All articles
Backend1 min read

Date and Time with java.time

The old Date and Calendar classes were mutable and error-prone. The java.time API models instants, dates, and zones cleanly and immutably.

S

Swapnika Voora

Author

java.util.Date mixed instants with human dates and was mutable to boot. The java.time package separates these concepts into clear, immutable types.

Choose the right type

Use Instant for machine timestamps, LocalDate for calendar dates, and ZonedDateTime when a time zone matters.

Times.java
Instant now = Instant.now();                       // UTC timestamp
LocalDate today = LocalDate.now();                 // no time, no zone
ZonedDateTime meeting = ZonedDateTime.of(
    2026, 5, 1, 9, 30, 0, 0, ZoneId.of("America/New_York"));

Do arithmetic safely

Durations and periods make offsets explicit and DST-aware.

Math.java
Instant deadline = now.plus(Duration.ofHours(48));
LocalDate nextMonth = today.plus(Period.ofMonths(1));

Takeaways

  • Store and transmit timestamps as UTC Instant; convert to zones only for display.
  • Never use Date or Calendar in new code.
  • Use DateTimeFormatter (immutable, thread-safe) instead of SimpleDateFormat.

Persist times as UTC in the database and apply the user's zone at the edge, so comparisons and sorting stay correct.

#java#date-time#best-practices

More in Backend