Java 8:如何从Epoch值创建ZonedDateTime?

时间:2022-06-05 16:04:32

Java 8's LocalDateTime has an ofEpochSecond method. Unfortunately, there is no such method in the ZonedDateTime. Now, I have an Epoch value and an explicit ZoneId given. How do I get a ZonedDateTime out of these?

Java 8的LocalDateTime有一个ofEpochSecond方法。不幸的是,ZonedDateTime中没有这样的方法。现在,我有一个Epoch值和一个明确的ZoneId给出。如何从中获取ZonedDateTime?

1 个解决方案

#1


62  

You should be able to do this via the Instant class, which can represent a moment given the epoch time. If you have epoch seconds, you might create something via something like

你应该可以通过Instant类来做到这一点,它可以代表一个给定时期的时刻。如果你有纪元秒,你可以通过类似的东西创造一些东西

Instant i = Instant.ofEpochSecond(t);
ZonedDateTime z = ZonedDateTime.ofInstant(i, zoneId);

#1


62  

You should be able to do this via the Instant class, which can represent a moment given the epoch time. If you have epoch seconds, you might create something via something like

你应该可以通过Instant类来做到这一点,它可以代表一个给定时期的时刻。如果你有纪元秒,你可以通过类似的东西创造一些东西

Instant i = Instant.ofEpochSecond(t);
ZonedDateTime z = ZonedDateTime.ofInstant(i, zoneId);