【问题标题】:how to handle edge case when using Java.time to convert date time to epoch使用 Java.time 将日期时间转换为纪元时如何处理边缘情况
【发布时间】:2020-05-06 01:57:15
【问题描述】:

这是我将日期时间转换为纪元时间戳的代码,有一种情况我不知道如何处理,如果时间戳中包含区域信息并且没有作为第三个参数传递给该函数,它将无论时间戳中的时区是什么时区,总是转换为UTC,如何解决这个问题?

  time_to_epoch(List(JString("2007-12-03T10:15:30 CET"), JString("yyyy-MM-dd'T'HH:mm:ss z"))) shouldEqual JString("1196669730000")

time_to_epoch(List(JString("2007-12-03T10:15:30+02:00"), JString("yyyy-MM-dd'T'HH:mm:ssXXX"), JString("CEST" ))) shouldEqual JString("1196669730000") time_to_epoch(List(JString("2007-12-03T10:15:30 CEST"), JString("yyyy-MM-dd'T'HH:mm:ss z"))) shouldEqual JString("1196673330000")

 whatever timezone in the timestamp, the result is wrong, i.e, CEST(+02:00), output (+01:00), America/Mexico_City(+05:00), output (+04:00)

【问题讨论】:

  • 如果您不想丢失有关时区的信息,请使用ZonedDateTime

标签: scala java-time


【解决方案1】:

如果时区数据可以是timestamp 字符串的一部分,那么无论是否默认提供,您都应该让它覆盖timezone 字符串。

formatter.parseBest(timestamp, ZonedDateTime.from _
                             , LocalDateTime.from _
                             , LocalDate.from _) match {
  case zdt: ZonedDateTime =>
    JString(zdt.toInstant().toEpochMilli.toString)
  case ldt: LocalDateTime =>
    . . .

【讨论】:

  • 我试过了,但这两种情况有不同的结果..(编辑代码)
  • @zzxdw;您已将我的答案合并到问题代码中,然后更改了问题的重点。您添加了测试示例,但没有包含您获得的结果。 (我的测试代码都通过了。)请将每个问题集中在 one 问题上,并用清晰简洁的代码演示 one 问题。
猜你喜欢
  • 2012-05-14
  • 2012-09-06
  • 2018-04-24
  • 2011-12-06
  • 2012-11-08
  • 2019-01-15
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
相关资源
最近更新 更多