java.time.OffsetDateTime:无法从TemporalAccessor获取OffsetDateTime

java.time.OffsetDateTime:无法从TemporalAccessor获取OffsetDateTime,java,java-time,timezone-offset,datetime-parsing,java.time.instant,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).withResol

我试图使用
“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)
我做错了什么?

试试这个:

LocalDateTime.parse("20140726080320+0400",
    new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmssZ").toFormatter())
.atOffset(ZoneOffset.UTC)
报税表:

2014-07-26T08:03:20



这是错误的,因为它忽略了偏移量(+0400),然后将日期/时间设置为UTC-这将在格式模式字符串中为纪年的纪元秒给出不正确的值。严格地说,2014年可以表示公元前2014年(“基督之前”)或2014年CE(“安诺多米尼”)。显然,具有严格解析器样式的格式化程序反对这种歧义

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

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

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

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

如果只存在年代,且模式为smart或LENTE,则假定当前年代(CE/AD)。在严格模式下,不假设纪元,纪元的年份保持不变


我必须再次查找,但我要说您的时区格式
Z
是错误的。从DateTimeFormatter.java:
*符号表示演示示例
*Z zone offset-Z+0000-0800; -08:00;中有3种分区偏移的可能性:Z、X和X。也许XX或XX工作得更好,如偏移量X和X下所述:仅仅从OP的代码中删除
.withResolverStyle(STRICT)
不是更简单吗?然而,我怀疑OP把它放在那里是有原因的,所以最好能找到一个使用严格格式化程序的解决方案。