如何使用“d.LLLL YYYY”模式从日期字符串创建 java.time.LocalDate?

neu*_*242 4 java parsing date java-8

我正在尝试创建一个 LocalDate 对象:

LocalDate date = LocalDate.parse(
    "1. juli 2014", 
    DateTimeFormatter.ofPattern("d. LLLL YYYY", new Locale("nb", "NO"));
Run Code Online (Sandbox Code Playgroud)

但我得到一个例外:

java.time.format.DateTimeParseException: Text '1. juli 2014' could not be parsed: 
    Unable to obtain LocalDate from TemporalAccessor: 
    {WeekBasedYear[WeekFields[MONDAY,4]]=2014, MonthOfYear=7, DayOfMonth=1},
    ISO of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1919)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1854)
at java.time.LocalDate.parse(LocalDate.java:400)
Run Code Online (Sandbox Code Playgroud)

该异常似乎表明那里有正确的数据(“juli”是挪威语,是第 7 个月)。

neu*_*242 5

所以,我找到了解决方案,尽管这可能是一个 Java 8 bug,正如 @NimChimpsky 评论的那样。

通过使用"d. LLLL yyyy"(使用年份)而不是"d. LLLL YYYY"(使用基于周的年份),解析将按预期进行。