java - Jodatime IllegalInstantException 异常

标签 java android datetime jodatime android-jodatime

我几乎尝试了有关此代码 fragment 的所有内容,但仍然遇到 IllegalInstentException。

public int getDateDay() {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
    DateTime dt;
    try {
        dt = formatter.parseDateTime(date);
    } catch (IllegalInstantException e) {
        dt = formatter.parseLocalDateTime(date).toDateTime();
    }
    return dt.getDayOfMonth();
}

Fatal Exception: org.joda.time.IllegalInstantException Illegal instant due to time zone offset transition (daylight savings time 'gap'): 2018-10-21T00:00:00.000 (America/Sao_Paulo) keyboard_arrow_up arrow_right org.joda.time.chrono.ZonedChronology.localToUTC (ZonedChronology.java:157) org.joda.time.chrono.ZonedChronology.getDateTimeMillis (ZonedChronology.java:122) org.joda.time.chrono.AssembledChronology.getDateTimeMillis (AssembledChronology.java:133) org.joda.time.base.BaseDateTime. (BaseDateTime.java:257) org.joda.time.DateTime. (DateTime.java:532) org.joda.time.LocalDateTime.toDateTime (LocalDateTime.java:750) org.joda.time.LocalDateTime.toDateTime (LocalDateTime.java:731)

最佳答案

输入的日期似乎无效。这个问题已经在这个page中讨论过.

原因:

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.

可能的解决方案如下:

  • Use LocalDateTime, as all local date-times are valid.

  • When converting a LocalDate to a DateTime, then use toDateTimeAsStartOfDay() as this handles and manages any gaps.

  • When parsing, use parseLocalDateTime() if the string being parsed has no time-zone.

关于java - Jodatime IllegalInstantException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52609641/

相关文章:

java - 预期对 'String' 原始类型进行拆箱,但返回 null

java - 使用 ANT 构建 DMG 文件的跨平台方式?

java - 发生未知错误,请检查 HTTP 结果代码和服务器响应的内部异常

c++ - 将 wxString 转换为 time_t

javascript - 任何使用 Moment.js 解析时间字符串但忽略时区信息的方法?

java - 如何在不使用 setter 的情况下从子类访问父类(super class)中的私有(private)字段?

java - AtomicIntegerArray 与 AtomicInteger[]

android - camerasource.takePicture() 在某些设备中保存旋转的图像

java - Inflate NavigationView 在 Android 4.4 及更低版本中导致异常

python - 字符串到日期时间转换 - 在日期-月份日期中指定年份