要将时间戳转换为 OffsetDateTime,可以使用 Instant 类和 ZoneOffset 类的组合。下面是一个示例代码:

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        long timestamp = 1612345678L; // 时间戳

        Instant instant = Instant.ofEpochSecond(timestamp); // 创建 Instant 对象
        ZoneOffset offset = ZoneOffset.ofHours(8); // 设置时区偏移量

        OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(instant, offset); // 将 Instant 对象转换为 OffsetDateTime 对象

        System.out.println(offsetDateTime);
    }
}

在上面的示例中,我们首先创建了一个 Instant 对象,该对象表示从 1970 年 1 月 1 日 00:00:00 开始的指定时间戳。然后,我们创建了一个 ZoneOffset 对象,该对象表示与 UTC 的时区偏移量。最后,我们使用 OffsetDateTime 的 ofInstant() 方法将 Instant 对象和 ZoneOffset 对象组合起来,创建一个 OffsetDateTime 对象。

运行上面的代码,将输出转换后的 OffsetDateTime 对象。注意,这里我们假设时间戳是以秒为单位的,如果是以毫秒为单位的时间戳,需要将 Instant.ofEpochSecond(timestamp) 改为 Instant.ofEpochMilli(timestamp)。

Java 时间戳转换为 OffsetDateTime 详解

原文地址: https://www.cveoy.top/t/topic/fxqr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录