将unix时间戳转换为ISO 8601,我使用的是.toDateTime()方法,如果我想在scala中把ISO 8601时间戳转换为unix时间戳呢?
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
首先--使用 java.time
包,它是基于Joda Time的(如果你使用的是很老的JVM,它没有 java.time
). 你的代码看起来像 java.sql
时间函数 - 避免使用。
从你的代码来看,你似乎想取epoch并返回格式化的字符串,并在途中确认时区。
Epoch到LocalDateTime。
java.time.LocalDateTime.ofEpochSecond(1587416590, 0, java.time.ZoneOffset.UTC)
它们是: epoch秒,纳秒和时间偏移。
要将LocalDateTime转换为字符串,你需要一个格式,例如。
localDateTime.format(java.time.format.DateTimeFormatter.ISO_DATE_TIME)
如果你有一个定义为字符串的目标格式,你可以建立格式为:
val formatter = java.time.format.DateTimeFormatter.ofPattern(format)
All in all:
java.time.LocalDateTime.ofEpochSecond(
epochSeconds,
nanosIfYouHaveThem,
offset
).format(java.time.format.DateTimeFormatter.ofPattern(targetFormat))
如果你想做相反的事情? 你就用。
java.time.LocalDateTime.parse(
timestamp,
format
).toEpochSecond(offset)