Dates and times with java.time

Core Java · lesson 16 of 42 · 4 min read

Pick the right date-time type, do calendar maths safely, and handle time zones.

Open this lesson in the learning hub

Key points

  • java.time replaced Date and Calendar. Every type is immutable and thread-safe.
  • LocalDate is a date, LocalTime a time, LocalDateTime both — and none of them carry a time zone.
  • Use Instant for a machine timestamp on the UTC timeline, and ZonedDateTime when the zone actually matters.
  • Every plusX and minusX returns a new object; the original is never modified.
  • Duration measures elapsed time (hours, seconds). Period measures calendar amounts (years, months, days).
  • Format with DateTimeFormatter. Store timestamps in UTC and convert to a zone only when you display them.

Example

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate java17 = LocalDate.of(2021, 9, 14);
        LocalDate java21 = LocalDate.of(2023, 9, 19);

        System.out.println("Java 17 shipped on a " + java17.getDayOfWeek());
        System.out.println("plusYears(2) -> " + java17.plusYears(2) + ", original untouched: " + java17);
        System.out.println("days between: " + ChronoUnit.DAYS.between(java17, java21));

        Period gap = Period.between(java17, java21);
        System.out.println("period: " + gap.getYears() + "y " + gap.getMonths() + "m " + gap.getDays() + "d");

        LocalDateTime meeting = LocalDateTime.of(2024, 3, 1, 9, 30);
        System.out.println("formatted: " + meeting.format(DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm", Locale.ENGLISH)));
        System.out.println("plus 90 minutes: " + meeting.plus(Duration.ofMinutes(90)));

        ZonedDateTime london = meeting.atZone(ZoneId.of("Europe/London"));
        System.out.println("London: " + london);
        System.out.println("Tokyo : " + london.withZoneSameInstant(ZoneId.of("Asia/Tokyo")));
    }
}

java.time is immutable by design: keep instants in UTC, convert only to display.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.