← 中文资源

简体中文版本

withZoneSameInstant 与 withZoneSameLocal 对比

换时区有两个方向:withZoneSameInstant 保住同一时刻、墙钟平移;withZoneSameLocal 保住墙钟数字、时刻被改写。两者相差恰好是时区偏移,选错就是九小时的会议错位。

阅读英文原文

实现说明

withZoneSameInstant 与 withZoneSameLocal 对比的核心是类 ZoneConverter和函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 sameInstant:、sameLocal:、instant gap hours:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「withZoneSameInstant 与 withZoneSameLocal 对比」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 sameInstant:、sameLocal:、instant gap hours: 标签标明各步骤。

核心语句

ZonedDateTime utcInstant = tokyoMeeting.withZoneSameInstant(ZoneId.of("UTC"));
ZonedDateTime utcLocal = tokyoMeeting.withZoneSameLocal(ZoneId.of("UTC"));

代码示例

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZoneConverter {

    public static void main(String[] args) {
        ZonedDateTime tokyoMeeting = ZonedDateTime.of(
                LocalDateTime.of(2026, 11, 19, 14, 0), ZoneId.of("Asia/Tokyo"));

        // withZoneSameInstant:同一时刻换时区,墙钟数字随偏移平移
        ZonedDateTime utcInstant = tokyoMeeting.withZoneSameInstant(ZoneId.of("UTC"));
        System.out.println("sameInstant: " + utcInstant);

        // withZoneSameLocal:墙钟数字不变,时刻本身被改写(versus 对照)
        ZonedDateTime utcLocal = tokyoMeeting.withZoneSameLocal(ZoneId.of("UTC"));
        System.out.println("sameLocal:   " + utcLocal);

        // 两条转换相差的正是两个时区之间的偏移
        long diffHours = Math.abs(Duration.between(
                utcInstant.toInstant(), utcLocal.toInstant()).toHours());
        System.out.println("instant gap hours: " + diffHours);
    }
}