← 中文资源

简体中文版本

ZoneId 时区规则解析时刻偏移

ZoneRules 把 UTC 时刻解析成时区此刻的真实偏移,ofHoursMinutes 构造固定偏移,UTC+01:00 规范化后就是 ZoneOffset,可用时区来自 JDK 内置的 IANA tzdb 副本,数量随 JDK 版本变化。

阅读英文原文

实现说明

逻辑集中在类 ZoneLookups和函数 main里。

使用要点

  • 演示输出是带标签的(offset=、custom=、normalized=),每个操作都会留下自己的一行标注。

常见问题

运行「ZoneId 时区规则解析时刻偏移」会打印什么?

运行文件本身,offset=、custom=、normalized= 这些前缀各对应一段演示逻辑。

核心语句

ZoneOffset custom = ZoneOffset.ofHoursMinutes(5, 30);
Instant now = Instant.parse("2026-11-21T00:00:00Z");
ZoneId zone = ZoneId.of("Asia/Shanghai");

代码示例

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

public class ZoneLookups {

    public static void main(String[] args) {
        ZoneId zone = ZoneId.of("Asia/Shanghai");
        Instant now = Instant.parse("2026-11-21T00:00:00Z");

        // ZoneRules resolve any instant to the zone's real offset at that moment
        System.out.println("offset=" + zone.getRules().getOffset(now));

        // build a fixed offset by hand: hours plus minutes
        ZoneOffset custom = ZoneOffset.ofHoursMinutes(5, 30);
        System.out.println("custom=" + custom);

        // fixed IDs like UTC+01:00 normalize to the ZoneOffset itself
        System.out.println("normalized=" + ZoneId.of("UTC+01:00").normalized());

        // the zone list comes from the JDK's bundled IANA tzdb copy: the count varies with JDK updates, not OS tzdata
        System.out.println("zones registered: " + ZoneId.getAvailableZoneIds().size());
    }
}