Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

ZoneId.of: select a time zone by ID

Use `ZoneId.of` to select a regional time zone or fixed UTC offset and display the same instant in Warsaw, New York, and Tokyo.

Version: Java SE 21

Syntax

import java.time.ZoneId;
import java.util.Map;

// Static method signatures in java.time.ZoneId:
public static ZoneId of(String zoneId)
public static ZoneId of(String zoneId, Map<String, String> aliasMap)

// Example calls:
ZoneId.of("Europe/Warsaw")
ZoneId.of("+02:00")
ZoneId.of("office", Map.of("office", "Europe/Warsaw"))

ZoneId.of(String) is a static factory method on java.time.ZoneId. It takes a non-null ID and returns a zone whose rules are available in the runtime. It does not create a date or time by itself.

Europe/Warsaw, America/New_York, and Asia/Tokyo are region IDs from the default IANA TZDB. Preserve their letter case. A region's offset depends on its rules and the instant, so it can change, for example at a daylight saving transition. +02:00 and Z return a fixed ZoneOffset. UTC, GMT, and UT keep their IDs with a zero offset; UTC+02:00 keeps the UTC prefix and has a fixed offset.

ZoneId.of(String, Map<String, String>) first substitutes a mapped value when the ID has a matching key, then resolves the resulting ID as the one-argument overload does. The map must not be null. You can explicitly pass ZoneId.SHORT_IDS for legacy abbreviations; do not assume abbreviations are unambiguous or that the one-argument overload uses this map.

Invalid syntax causes DateTimeException; a well-formed but unavailable region ID causes ZoneRulesException, a subclass of DateTimeException. Handle these errors explicitly rather than silently falling back to the default zone. In the example, Instant.atZone creates a ZonedDateTime: the local representation changes, but the instant does not. Available region IDs and rules depend on the runtime's time-zone data.

Examples

import java.time.Instant;
import java.time.ZoneId;

public class ZoneIdExample {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2024-07-01T12:00:00Z");
        String[] zoneIds = {"Europe/Warsaw", "America/New_York", "Asia/Tokyo"};

        for (String id : zoneIds) {
            ZoneId zone = ZoneId.of(id);
            System.out.println(instant.atZone(zone));
        }
    }
}

Result

2024-07-01T14:00+02:00[Europe/Warsaw]
2024-07-01T08:00-04:00[America/New_York]
2024-07-01T21:00+09:00[Asia/Tokyo]

Each line shows the same fixed instant as a local date and time, followed by the UTC offset and the region ID in square brackets.

Related lessons

  • Java · Lesson 59 · Intermediate · Version: 2

Sources