【发布时间】:2017-09-26 23:20:06
【问题描述】:
我正在尝试将字符串转换为 LocalDate 对象。但我收到以下错误。
private LocalDate getLocalDate(String year) {
String yearFormatted = "2015-01-11";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd");
LocalDate dateTime = LocalDate.parse(yearFormatted, formatter);
return dateTime;
}
这是错误
Caused by: java.time.format.DateTimeParseException: Text '2015-01-11' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=11, WeekBasedYear[WeekFields[SUNDAY,1]]=2015, MonthOfYear=1},ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920) ~[na:1.8.0_102]
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855) ~[na:1.8.0_102]
at java.time.LocalDate.parse(LocalDate.java:400) ~[na:1.8.0_102]
【问题讨论】:
-
试试
DateTimeFormatter.ofPattern("yyyy-MM-dd"); -
你能解释一下为什么吗?
-
因为
LocalDate不知道如何处理基于周的年份(格式化程序中的“Y”)。它需要一年('u')或年代('y')