我已经阅读了手册,完全不知道为什么此代码不起作用。
// Date Entered must be valid
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy")
.withResolverStyle(ResolverStyle.STRICT);
try {
String dateEntered = lossDateMonth + "/" + lossDateDay + "/" + lossDateYear; // Slash to match UI
System.out.println(dateEntered);
LocalDate dateParsed = LocalDate.parse(dateEntered, dateTimeFormatter);
println语句打印:2015年7月29日
最后一行抛出异常:java.time.format.DateTimeParseException:无法解析文本“ 07/29/2015”:无法从TemporalAccessor获取LocalDate:{YearOfEra = 2015,DayOfMonth = 29,MonthOfYear = 7},类型为java.time.format的ISO 。解析
我阅读了此手册,它说如果您尝试解决一个不存在的日期(例如9月31日),则会发生这种情况。即使出现错误,解析器似乎也知道我在问2015年7月29日左右,所以我在这里做错了什么?
用"MM/dd/yyyy"
替换样式"MM/dd/uuuu"
。看一下DateTimeFormatter和IsoChronology。问题在于,当使用.withResolverStyle(ResolverStyle.STRICT)
时,格式化程序期望由uuuu
提供的年份的唯一标识符,其中yyyy
是时代。这是严格验证值。通过uuuu
可以为负的事实来给出唯一性。