scala - 如何在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
解决方案
首先 - 使用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)
推荐阅读
- javascript - 如何在 ReactJS 上渲染代码生成的 SVG?
- linux - 如何使用命令行脚本动态配置 haproxy?
- android - 仅从 SD 卡中读取名称中包含特定字符串的文件
- r - 如何遍历由 data.table 中的数字索引的变量?
- ruby-on-rails - Rails 生产控制台中没有控制台颜色
- genexus - 如何使用逗号分隔符“,”而不是“。” 十进制的genexus值?
- spss - 为什么我的语法无法计算新变量?
- ansible - Ansible:如何从 YAML 中的 JSON 响应中提取嵌套字典值
- shell - 在 shell 脚本中访问 cpp #define 预处理器变量?
- java - onActivityResult 返回值太晚