[英]How to convert an Epoch timestamp into an object of type java.time.Instant Accurately in Java?
I have a Spring Boot JPA Application that interacts with a 3rd party API.我有一个 Spring 启动 JPA 应用程序,它与第 3 方 API 交互。 The response payload of the API has a key API的响应payload有一个key
"created_at": 1591988071 “created_at”:1591988071
I need to parse this field into java.time.Instant so that I can do some comparisons with the value I have in the Database.我需要将此字段解析为 java.time.Instant 以便我可以与数据库中的值进行一些比较。 I have learned that I can use the below mentioned piece of code.我了解到我可以使用下面提到的一段代码。
Instant instant = Instant.ofEpochSecond(1591988071);
Output: Output:
2020-06-12T18:54:31Z
But to be honest, this output is off by a couple of hours.但老实说,这个 output 已经关闭了几个小时。
I found another approach, wherein if I use我找到了另一种方法,如果我使用
String dateAsText = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(1591988071 * 1000L));
System.out.println(dateAsText);
I get the desired output but in String format.我得到了所需的 output 但采用字符串格式。
2020-06-13 00:24:31
Can someone tell me how to obtain the above String output but converted into type java.time.Instant?有人可以告诉我如何获得上述字符串 output 但转换为 java.time.Instant 类型吗?
It is likely you're in a different timezone than UTC.您所在的时区可能与 UTC 不同。 The instant is giving you time in UTC.瞬间为您提供 UTC 时间。 That's indicated by the Z
at the end of your first output.这由您的第一个 output 末尾的Z
表示。
You would want to look at atZone你会想看看在Zone
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);
This gives you something you might expect这为您提供了您可能期望的东西
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.