date - Jodatime:从日期获取毫秒结果为 "Illegal instant"

标签 date parsing jodatime

  val date = "01-10-1967"
  val pattern = "dd-MM-yyyy"
  val formatter = DateTimeFormat.forPattern(pattern)
  formatter.parseMillis(date) // this line fails

最后一行失败并显示:

Cannot parse "01-10-1967": Illegal instant due to time zone offset transition (America/Argentina/Buenos_Aires)

知道为什么吗?

(JodaTime版本为2.3)

最佳答案

1967 年 10 月 1 日是阿根廷的一天,他们changed from standard time to summer time ,即在 00:00 添加 1 小时。

由于您没有提供具体时间,我假设它默认为 00:00,而这一天根本不存在。

比照。 the official faq :

What does 'Illegal instant due to time zone offset transition' mean? Joda-Time only allows the key classes to store valid date-times. For example, 31st February is not a valid date so it can't be stored (except in Partial). The same principle of valid date-times applies to daylight savings time (DST). In many places DST is used, where the local clock moves forward by an hour in spring and back by an hour in autumn/fall. This means that in spring, there is a "gap" where a local time does not exist. The error "Illegal instant due to time zone offset transition" refers to this gap. It means that your application tried to create a date-time inside the gap - a time that did not exist. Since Joda-Time objects must be valid, this is not allowed.

可能的解决方案可能是(取自常见问题解答):

  • 使用 LocalDateTime,因为所有本地日期时间均有效。
  • LocalDate 转换为 DateTime 时,请使用 toDateTimeAsStartOfDay(),因为它可以处理和管理任何间隙。
  • 解析时,如果解析的字符串没有时区,请使用 parseLocalDateTime()

既然您对时间信息不感兴趣,我想您甚至可能想将 formatter.parseMillis(date) 替换为 formatter.parseLocalDate(date)。如果由于某种原因您仍然需要毫秒,this Stack Overflow question可能有帮助。

关于date - Jodatime:从日期获取毫秒结果为 "Illegal instant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35189662/

相关文章:

java - 添加 Joda Time

jodatime - 纪元时间可以倒退多远?

java - 检测日期是否更改的最有效方法是什么?

javascript - jQuery uidatepicker 按钮图像不起作用

java - 除了 Jsoup 还有其他解析器吗?

regex - Lua文本解析、空格处理

java - struts2中的日期更改问题

sql - PostgreSQL 从日期类型获取年份作为整数

php - 如何评估在 PHP 中作为字符串传递的公式?

java - JodaTime:如何从 LocalTime 获取格式为 "HH:mm Z"的字符串表示形式