如何在Java中准确地将Epoch时间戳转换为java.time.Instant类型的对象?

How to convert an Epoch timestamp into an object of type java.time.Instant Accurately in Java?

我有一个 Spring 与第 3 方交互的引导 JPA 应用程序 API。 API 的响应负载有一个键

"created_at": 1591988071

我需要将此字段解析为 java.time.Instant,以便我可以与数据库中的值进行一些比较。 我了解到我可以使用下面提到的一段代码。

    Instant instant = Instant.ofEpochSecond(1591988071);

输出:

    2020-06-12T18:54:31Z

但老实说,这个输出会关闭几个小时。

我找到了另一种方法,其中如果我使用

    String dateAsText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            .format(new Date(1591988071 * 1000L));
    System.out.println(dateAsText);

我得到了想要的输出,但是是字符串格式。

    2020-06-13 00:24:31

谁能告诉我如何获得上述字符串输出但转换为类型 java.time.Instant ?

您所在的时区可能与 UTC 不同。即时为您提供 UTC 时间。这由第一个输出末尾的 Z 表示。

你会想看看 atZone

Instant instant = Instant.ofEpochSecond(1591988071);
System.out.println(instant);
final ZonedDateTime losAngeles = instant.atZone(ZoneId.of("America/Los_Angeles"));
System.out.println(losAngeles);
final ZonedDateTime mumbai = instant.atZone(ZoneId.of("UTC+0530"));
System.out.println(mumbai);

这给了你一些你可能期待的东西

2020-06-12T18:54:31Z
2020-06-12T11:54:31-07:00[America/Los_Angeles]
2020-06-13T00:24:31+05:30[UTC+05:30]