Java LocalDateTime from DateTimeFormatter
java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor
I ran into this error trying to use a ResolverStyle.STRICT date resolver on a DateTimeFormatter.
Here is the code that was causing the problem.
Note that the problem does not happen if you use the default ResolverStyle.SMART.
String INPUT_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseStrict() .appendPattern(INPUT_DATE_TIME_FORMAT).toFormatter().withResolverStyle(ResolverStyle.STRICT); startDTS = LocalDateTime.from(formatter.parse(dtsString));
The key is the input string specification. You must use the "uuuu" option for the date this specifies this date as a "proleptic-year", instead of "yyyy" which give you the "year-of-era".
String INPUT_DATE_TIME_FORMAT = "uuuu-MM-dd'T'HH:mm:ss.SSSZ";
The difference here is subtle because for any year in the the current era the "proleptic-year" and the "year-of-era" will actually be the same. The problem is that the DateTimeFormatter when put into STRICT mode will require you to be specific about the era so you must either specify the era in the date or spec your date as being proleptic. When operating in SMART mode the resolver makes the assumption that the year is in the current era (unless zero or negative)