首页 > 解决方案 > 如何在scala中将ISO 8601时间戳转换为unix时间戳

问题描述

为了将 unix 时间戳转换为 ISO 8601,我使用 .toDateTime() 方法,如果我想在 scala 中将 ISO 8601 时间戳转换为 unix 时间戳怎么办?</p>

for {
JString(format) <- Some(format)
JInt(timestamp) <- Some(timestamp)
JString(timezone) <- Some(timezone)
res <- JString(new DateTime(timestamp.toLong).toDateTime(DateTimeZone.forID(timezone)).toString(format))
} yield res
res

标签: scala

解决方案


首先 - 使用java.time基于 Joda Time 的包(如果你在非常旧的 JVM 上没有 JVM,请使用后者java.time)。您的代码看起来像java.sql时间函数 - 避免使用它们。

从您的代码中,您似乎想要采用纪元并返回格式化字符串并以一种方式确认时区。

纪元到 LocalDateTime:

java.time.LocalDateTime.ofEpochSecond(1587416590, 0, java.time.ZoneOffset.UTC)

它们是:纪元秒、纳秒和时间偏移。

要将 LocalDateTime 转换为 String ,您需要一种格式,例如:

localDateTime.format(java.time.format.DateTimeFormatter.ISO_DATE_TIME)

如果您将目标格式定义为字符串,则可以构建格式为:

val formatter = java.time.format.DateTimeFormatter.ofPattern(format)

总而言之:

java.time.LocalDateTime.ofEpochSecond(
  epochSeconds,
  nanosIfYouHaveThem,
  offset
).format(java.time.format.DateTimeFormatter.ofPattern(targetFormat))

如果你想反其道而行之?你用:

java.time.LocalDateTime.parse(
  timestamp,
  format
).toEpochSecond(offset)

推荐阅读