Ch. 7 · Java

Java Time Types and Zone-Aware Decisions

When to use Instant, LocalDateTime, ZonedDateTime and OffsetDateTime, and how daylight saving gaps and overlaps break naive date code.

~7 min readadvancedupdated Nov 1, 2026

A nightly job runs twice on the Sunday the clocks go back. A call booked for 10:00 shows up at the wrong hour for a colleague abroad. Both bugs come from storing a wall-clock time without a zone, or from adding 24 hours when the business meant “the same time tomorrow”. Questions such as “What is the difference between LocalDateTime and Instant?” and “How would you store a meeting time for users in different countries?” test whether you can avoid them by modelling time correctly.

A senior answer chooses the right type for each fact, explains daylight saving gaps and overlaps, and shows how to make time-dependent code testable. Keep zones and offsets apart while you read: a zone such as Europe/Paris is a set of rules that changes over history, while an offset such as +02:00 is one fixed number.

Which type to use for which fact

Use Instant for a point on the global timeline, such as when an event happened; it is what you store and compare. Use LocalDate and LocalDateTime for wall-clock values without a zone, such as a birthday or “9:00 on the calendar”. Use ZonedDateTime when local rules matter, for example scheduling “9:00 every day in Paris”, because it applies daylight saving transitions; OffsetDateTime carries a fixed offset and suits APIs and databases. Convert to a zone only at the edges, and inject a Clock so tests control “now”.

What each type knows, and DST gaps and overlaps

The main types differ in what they know:

Type Example Knows the zone rules Represents an exact moment
Instant 2026-03-29T01:30:00Z no (always UTC) yes
LocalDateTime 2026-03-29T02:30 no no
OffsetDateTime 2026-03-29T03:30+02:00 no, fixed offset yes
ZonedDateTime 2026-03-29T03:30+02:00[Europe/Paris] yes yes

A LocalDateTime is ambiguous until you attach a zone. “2026-11-01T01:30” is a different instant in New York and London, and in New York it happens twice that day.

Daylight saving transitions create two kinds of trouble. In a gap, clocks jump forward and some local times do not exist. In an overlap, clocks fall back and some local times occur twice. ZonedDateTime.of resolves them by documented rules: a time in a gap is shifted forward by the gap length, and a time in an overlap uses the earlier offset by default.

ZoneId paris = ZoneId.of("Europe/Paris");

// 2026-03-29: clocks jump from 02:00 to 03:00 in Paris
ZonedDateTime gap = ZonedDateTime.of(LocalDateTime.of(2026, 3, 29, 2, 30), paris);
System.out.println(gap);   // 2026-03-29T03:30+02:00[Europe/Paris]

// 2026-10-25: clocks fall back from 03:00 to 02:00
ZonedDateTime overlap = ZonedDateTime.of(LocalDateTime.of(2026, 10, 25, 2, 30), paris);
System.out.println(overlap);                       // 2026-10-25T02:30+02:00[Europe/Paris]
System.out.println(overlap.withLaterOffsetAtOverlap()); // 2026-10-25T02:30+01:00[Europe/Paris]
java

Arithmetic also depends on intent. plus(Duration.ofHours(24)) adds exact elapsed time, while plusDays(1) keeps the same local time on the next calendar day. Across a DST change they give different instants.

Pinning the Paris gap, overlap and arithmetic rules in tests

These assertions pin down the gap, overlap and arithmetic rules for Paris in 2026:

import static org.junit.jupiter.api.Assertions.*;
import java.time.*;
import org.junit.jupiter.api.Test;

class ZoneRulesTest {
    final ZoneId paris = ZoneId.of("Europe/Paris");

    @Test
    void gapShiftsForward() {
        var zdt = ZonedDateTime.of(LocalDateTime.of(2026, 3, 29, 2, 30), paris);
        assertEquals(LocalTime.of(3, 30), zdt.toLocalTime());
    }

    @Test
    void overlapDefaultsToEarlierOffset() {
        var zdt = ZonedDateTime.of(LocalDateTime.of(2026, 10, 25, 2, 30), paris);
        assertEquals(ZoneOffset.ofHours(2), zdt.getOffset());
        assertEquals(ZoneOffset.ofHours(1), zdt.withLaterOffsetAtOverlap().getOffset());
    }

    @Test
    void plusDaysVersusDuration() {
        var start = ZonedDateTime.of(2026, 3, 28, 9, 0, 0, 0, paris);
        assertEquals(9, start.plusDays(1).getHour());
        assertEquals(10, start.plus(Duration.ofHours(24)).getHour());
    }
}
java

Run java -version and check the JDK’s tzdata version if results differ; zone rules ship with the JDK and are updated in patch releases.

Modelling time in an application, from domain to tests

Classify each value: instant, local time or date

Ask what each value means. “The payment was captured” is an instant. “The shop opens at 09:00” is a local time plus the shop’s zone. “The contract starts on 2026-01-01” is a LocalDate. “A user’s birthday” is a LocalDate with no zone at all. Writing this down first prevents most bugs.

Store instants and zone ids, not formatted strings

record Event(UUID id, Instant occurredAt) {}

record Appointment(UUID id, LocalDateTime localStart, ZoneId zone) {
    Instant startInstant() {
        return localStart.atZone(zone).toInstant();
    }
}
java

For a future appointment, store the local time and the zone id rather than only an instant. If a government changes its zone rules before the appointment, the instant must be recomputed, while the user’s intended “10:00 local” stays the same. In PostgreSQL, store instants in a timestamptz column; plain JDBC reads and writes it as OffsetDateTime, and JPA providers such as Hibernate map Instant to it directly.

Convert to the viewer’s zone at the edges

Instant now = Instant.now(clock);
ZonedDateTime forUser = now.atZone(ZoneId.of(user.timeZone()));
String label = forUser.format(DateTimeFormatter.ofPattern("EEE d MMM, HH:mm", user.locale()));
java

Server code works in instants. The presentation layer converts to the viewer’s zone and locale.

plusDays or Duration?

ZonedDateTime start = ZonedDateTime.of(2026, 3, 28, 9, 0, 0, 0, paris);
start.plusDays(1);                    // 2026-03-29T09:00+02:00 (same wall-clock time)
start.plus(Duration.ofHours(24));     // 2026-03-29T10:00+02:00 (24 elapsed hours)
java

Daily reminders want plusDays. Session timeouts and rate limits want Duration.

Inject a Clock

class InvoiceService {
    private final Clock clock;
    InvoiceService(Clock clock) { this.clock = clock; }

    boolean isOverdue(Invoice inv) {
        return LocalDate.now(clock.withZone(inv.zone())).isAfter(inv.dueDate());
    }
}
java

Production passes Clock.systemUTC(); tests pass Clock.fixed(...).

A 02:30 Paris job that drifted, then ran twice

Picture a reporting job scheduled to run “every day at 02:30 Europe/Paris”, where lastRun is the local time at which the job last fired and the next run is computed like this:

LocalDateTime next = lastRun.plusHours(24);
Instant fireAt = next.atZone(paris).toInstant();
java

On the spring-forward night, 02:30 does not exist, so atZone shifts it to 03:30. The job fires at 03:30, lastRun becomes 03:30, and every later run is an hour late: the schedule has drifted for good. The autumn night has the opposite problem, because 02:30 happens twice. A scheduler that fires whenever the local wall clock reads 02:30 runs the job at both occurrences. One that adds a fixed 24-hour Duration to the previous instant fires at the first 02:30 on 25 October and then at 01:30 local time from 26 October on. Finance would see two reports one night, or reports an hour early for the rest of the winter.

The fix keeps the local target time constant and lets the zone rules decide each instant, with an explicit policy for gaps and overlaps:

static Instant nextRun(LocalDate day, ZoneId zone) {
    LocalDateTime target = day.atTime(2, 30);
    ZonedDateTime zdt = ZonedDateTime.of(target, zone);   // gap: moves to 03:30
    return zdt.withEarlierOffsetAtOverlap().toInstant();   // overlap: run once, at the first 02:30
}
java

Each run computes from the calendar date, not the previous instant, so drift cannot accumulate. Scheduling batch jobs in UTC avoids the question entirely; that is a valid answer if the business accepts that local run times shift with DST.

Time-handling habits that cause production bugs

  • Storing LocalDateTime for events. Without a zone, nobody can tell which moment it was.
  • Using a fixed offset for a region. +01:00 is wrong for Paris half the year. Use ZoneId.of("Europe/Paris").
  • Adding 24 hours for “tomorrow”. Across DST, that is not the same wall-clock time.
  • Calling LocalDate.now() without a zone or clock. It silently uses the server’s default zone, which differs between laptops and containers.
  • Using three-letter zone ids. EST and IST are ambiguous; IST can mean India, Ireland or Israel.

Interview question: a New York call with a London colleague

A user in New York books a call for “10:00 on 2026-11-01” with a colleague in London. What do you store, and what time does the London colleague see?

A strong answer stores the intent and the zone id

Store the organiser’s intent: LocalDateTime 2026-11-01T10:00 and ZoneId America/New_York, plus the computed Instant for indexing. New York falls back to standard time at 02:00 on 2026-11-01, so 10:00 that day is unambiguous at offset -05:00, which is 15:00 UTC. London has already returned to GMT on 2026-10-25, so the London colleague sees 15:00. A week earlier, the gap between the cities would have been only four hours, because the two regions change clocks on different dates. Storing the zone id rather than a fixed offset is what lets the system get both weeks right, and keeping the local intent lets you recompute if zone rules change before the meeting.

Follow-ups: epoch millis, Period vs Duration, legacy Date

Is Instant the same as epoch milliseconds? It represents the same timeline with nanosecond precision. Instant.toEpochMilli() converts, truncating sub-millisecond detail.

What is the difference between Period and Duration? Period is date-based (years, months, days) and respects calendars; Duration is exact seconds and nanoseconds.

Are java.time types thread-safe? Yes. They are immutable, and DateTimeFormatter is too, unlike the old SimpleDateFormat.

How do you convert legacy Date? date.toInstant() and Date.from(instant). For java.sql.Timestamp, use toInstant() or toLocalDateTime(), knowing which you mean.

Next: immutability, records and the java.time docs

Practise more with the Java interview questions and the Java MCQs. Related notes: immutable objects and defensive copies and records and shallow immutability. The type overview lives in the java.time package documentation.

More in Java

esc