java 8 日期时间分析错误

java 8 datatime parse error

我正在尝试将字符串转换为 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]

正如the documentation所说,格式模式中的大写Y是week-based-year,即周数所属的年份。这并不总是与日历年相同(尽管通常如此)。 Java 足够聪明,可以识别它无法确定从基于周的年、月和日中获取日期,因此它会抛出异常。

由于您的字符串格式与默认 LocalDate 格式 (ISO 8601) 一致,最简单的解决方案是完全删除格式化程序并执行以下操作:

    LocalDate dateTime = LocalDate.parse(yearFormatted);

通过此更改,您方法 returns 日期 2015-01-11 正如我认为您所期望的那样。另一个修复方法是将 YYYY 替换为小写的 yyyy 代表年份或 uuuu 代表有符号的年份(其中 0 是 1 BC,-1 是 2BC,等等)。