我有一个纪元秒和一个 zoneId (见下面的 method1
)。
它可以转换为 LocalDateTime
使用系统默认的 zoneId,但我找不到将纪元秒转换为 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 。
原文由 Renkai 发布,翻译遵循 CC BY-SA 4.0 许可协议
以下是如何从
ZoneOffset
获得ZoneId
:注意:
ZoneId
根据时间点和特定地点的历史可以有不同的偏移量。所以选择不同的 Instants 会导致不同的偏移量。NB2:
ZoneId.of()
can return aZoneOffset
instead ofZoneId
ifUTC+3
/GMT+2
/etc is passed as opposed到像Africa/Cairo
这样的时区。因此,如果传递了 UTC/GMT 偏移量,则不会考虑Instant
的历史/地理/夏令时信息 - 您只需使用指定的偏移量即可。