我有一个纪元秒和一个 zoneId(参见下面的 method1
)。
可以使用系统默认 zoneId 转换为 LocalDateTime
,但我没有找到将纪元秒转换为 LocalDateTime
的方法(请参阅 method2
下面),因为没有 ZoneOffset.systemDefault
。我认为这很模糊。
import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset}
val epochSecond = System.currentTimeMillis() / 1000
// method1
LocalDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), ZoneId.systemDefault())
// method2
LocalDateTime.ofEpochSecond(epochSecond, 0, ZoneOffset.MAX)
注意
上面提供的源代码是Scala .
最佳答案
以下是如何从 ZoneId
获取 ZoneOffset
:
Instant instant = Instant.now(); //can be LocalDateTime
ZoneId systemZone = ZoneId.systemDefault(); // my timezone
ZoneOffset currentOffsetForMyZone = systemZone.getRules().getOffset(instant);
NB:ZoneId
可以有不同的偏移量,具体取决于时间点和特定地点的历史。所以选择不同的 Instant 会导致不同的偏移量。
NB2: ZoneId.of()
可以返回 ZoneOffset
而不是 ZoneId
如果 UTC+3
GMT+2
/etc 被传递,而不是像 Africa/Cairo
这样的时区。因此,如果传递了 UTC/GMT 偏移量,则不会考虑 Instant
的历史/地理/夏令时信息 - 您只需使用指定的偏移量即可。
关于java - 有没有办法在 Java 8 中将 ZoneId 转换为 ZoneOffset?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32626733/