java.time.OffsetDateTime : Unable to obtain OffsetDateTime from TemporalAccessor

标签 java java-time timezone-offset datetime-parsing java.time.instant

我尝试使用 "yyyyMMddHHmmssZ" 格式解析 "20140726080320+0400",如下所示:

System.out.println("********************" + OffsetDateTime
    .parse("20140726080320+0400",
        DateTimeFormatter.ofPattern("yyyyMMddHHmmssZ").withChronology(IsoChronology.INSTANCE).withResolverStyle(STRICT))
    .toEpochSecond()); 

我一直遇到这个异常:

java.time.format.DateTimeParseException: Text '20140726080320+0400' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {OffsetSeconds=14400, DayOfMonth=26, YearOfEra=2014, MonthOfYear=7},ISO resolved to 08:03:20 of type java.time.format.Parsed
    at java.time.format.Parsed.getLong(Parsed.java:203)
    at java.time.Instant.from(Instant.java:373)
    at java.time.OffsetDateTime.from(OffsetDateTime.java:365)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.OffsetDateTime.parse(OffsetDateTime.java:402)

我做错了什么?

最佳答案

格式模式字符串中的

yyyy 表示纪元的年份。严格来说,2014 年可以表示 2014 BCE(“基督之前”)或 2014 CE(“anno Domini”)。显然,具有严格解析器风格的格式化程序反对这种歧义。

解决方案是使用 uuuu 表示年份。这是一个有符号的年份,其中 0 表示公元前 1 年,-1 表示公元前 2 年,依此类推。因此没有歧义:

    System.out.println("********************"
            + OffsetDateTime.parse("20140726080320+0400",
                                DateTimeFormatter.ofPattern("uuuuMMddHHmmssZ")
                                        .withChronology(IsoChronology.INSTANCE)
                                        .withResolverStyle(STRICT))
                        .toEpochSecond());

这会打印

********************1406347400

这与 IsoChronology 解析不同解析器样式的日期的方式有关,如 javadoc 中所述。 :

If only the YEAR_OF_ERA is present, and the mode is smart or lenient, then the current era (CE/AD) is assumed. In strict mode, no era is assumed and the YEAR_OF_ERA is left untouched.

关于java.time.OffsetDateTime : Unable to obtain OffsetDateTime from TemporalAccessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48263389/

相关文章:

java - 在 java.time 中从 `DateTimeFormatter.ofLocalized…` 生成的本地化字符串中强制使用 4 位数年份

java - 我想通过 JAXB 将带有 java.time.Localdate (JSR-310) 的对象转换为 XML,但输出错误

java - 具有夏令时的 GregorianCalendar.set() 行为

python - datetime.now(tz) 和 datetime(year,month,day,tzinfo=tz) 没有相同的 UTC 偏移量

java - 如何通过值查找枚举

java - 日文字体显示问题

java - 如何正确使用 java.lang.Terminator?

Java 8 文档日期时间教程错误

c# - Windows 7时区规则是否存在缺陷

java - PrivilegedActionException 试图从 JavaScript 调用签名的 Java applet