Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Time and zones in Java

Time and zones in Java: The java.time API separates an Instant on the timeline, a Duration, a LocalDate, and a ZonedDateTime governed by ZoneId rules.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

time

The java.time API separates an Instant on the timeline, a Duration, a LocalDate, and a ZonedDateTime governed by ZoneId rules.

Inject Clock into code that reads the current time, store events as Instant values, and convert to a zone only at presentation boundaries.

LocalDateTime has neither a zone nor a unique instant; Period counts calendar units while Duration counts seconds and nanoseconds, so they are not interchangeable.

A DST transition can skip or repeat local times, zone rules can change, and adding one calendar day does not always mean adding 24 hours.

The DST crossing changes 01:30+01:00 to 04:30+02:00 while elapsed=2; Clock.fixed gives date=2024-03-31.

Examples

import java.time.*;
public class Main {
  public static void main(String[] args) {
    var instant=Instant.parse("2024-03-31T00:30:00Z");
    var zone=ZoneId.of("Europe/Warsaw");
    var start=instant.atZone(zone); var end=start.plusHours(2);
    System.out.println(start); System.out.println(end);
    System.out.println("elapsed="+Duration.between(start.toInstant(),end.toInstant()).toHours());
    System.out.println("date="+LocalDate.now(Clock.fixed(instant,zone)));
  }
}

Result

2024-03-31T01:30+01:00[Europe/Warsaw]
2024-03-31T04:30+02:00[Europe/Warsaw]
elapsed=2
date=2024-03-31

The DST crossing changes 01:30+01:00 to 04:30+02:00 while elapsed=2; Clock.fixed gives date=2024-03-31.

Sources