← 中文资源

简体中文版本

OffsetTime 携带固定偏移的时间

OffsetTime 是"时间 + 固定偏移":无日期、无 DST 时区规则;withOffsetSameLocal 保钟表读数、withOffsetSameInstant 保时刻,atDate 挂日期升格 OffsetDateTime。

阅读英文原文

实现说明

底层就是类 DailyCloseTime和函数 main。

使用要点

  • 演示输出是带标签的(close:、same local:、same instant:),每个操作都会留下自己的一行标注。

常见问题

运行「OffsetTime 携带固定偏移的时间」会打印什么?

整个文件跑完,输出行以 close:、same local:、same instant: 这类前缀开头。

核心语句

OffsetTime earlier = OffsetTime.of(LocalTime.of(9, 0), ZoneOffset.ofHours(-5));
OffsetTime close = OffsetTime.of(LocalTime.of(17, 30), ZoneOffset.ofHours(8));
OffsetTime sameInstant = close.withOffsetSameInstant(ZoneOffset.ofHours(5));

代码示例

import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

public class DailyCloseTime {

    public static void main(String[] args) {
        // 营业结束时间 17:30,固定 +08:00:只有时间没有日期,也没有时区规则
        OffsetTime close = OffsetTime.of(LocalTime.of(17, 30), ZoneOffset.ofHours(8));
        System.out.println("close: " + close);

        // withOffsetSameLocal:钟表时间不变,偏移换掉(17:30+08 → 17:30+05)
        OffsetTime relabeled = close.withOffsetSameLocal(ZoneOffset.ofHours(5));
        System.out.println("same local: " + relabeled);

        // withOffsetSameInstant:同一时刻换个偏移表达(17:30+08 → 14:30+05)
        OffsetTime sameInstant = close.withOffsetSameInstant(ZoneOffset.ofHours(5));
        System.out.println("same instant: " + sameInstant);

        // 比较 isAfter/isBefore 时按"同一隐含日期"对齐时刻后再比
        OffsetTime earlier = OffsetTime.of(LocalTime.of(9, 0), ZoneOffset.ofHours(-5));
        System.out.println("close after earlier instant: " + close.isAfter(earlier));

        // 挂上日期升格为 OffsetDateTime
        System.out.println("with date: " + close.atDate(java.time.LocalDate.of(2026, 11, 23)));
    }
}