我尝试使用 "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/