具有LocalDateTime的DateTimeParseException:无法从TemporalAccessor获取LocalDateTime

时间:2016-10-11 13:53:04

标签: java time

这是我的代码:

private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss");

LocalDateTime timeStamp = LocalDateTime.parse(string, formatter);

导致以下异常:

  

java.time.format.DateTimeParseException:Text'Oct 10 13:10:01'可以   无法解析:无法从TemporalAccessor获取LocalDateTime:   {MonthOfYear = 10,DayOfMonth = 10},ISO解析为13:10:01类型   java.time.format.Parsed

使用Java 1.8.0_31。

我确实环顾四周,发现了很多类似的问题,但是没有一个问题与这个问题完全匹配,并且提供的解决方案在这里不适用:

Here同一问题的原因是使用没有时间部分的LocalDateTime。正如你从预期中看到的那样,这不是这种情况。

我没有像this示例那样使用基于周的年份。

最后不像here我使用的是LocalDateTime,所以时区应该不是问题。但是因为它应该是bug in DateTimeFormatter我试图将格式化程序作为'formatter.withZone(ZoneId.systemDefault())'(建议的解决方法)传递,导致相同的异常。

2 个答案:

答案 0 :(得分:3)

LocalDateTime需要一年 - 否则格式化程序无法确定10月10日是在2016年还是在公元前452年。

您可以向DateTimeFormatter添加默认行为,例如:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MMM dd HH:mm:ss")
        .parseDefaulting(ChronoField.YEAR_OF_ERA, 2016)
        .toFormatter(Locale.ENGLISH);

或者通过以下方式使其更灵活地默认为当前年份:

        .parseDefaulting(ChronoField.YEAR_OF_ERA, Year.now().getValue())

答案 1 :(得分:1)

Answer by assylias是正确的,应该被接受。

MonthDay

如果您确实只想要一个月的值和一个没有任何年份的日期,例如定期的周年纪念/生日,那么请使用MonthDay课程。

要将字符串解析为MonthDay,请调用MonthDay.parse并传递与您的字符串输入格式匹配的DateTimeFormatter

DateTimeFormatter f = 
    DateTimeFormatter.ofPattern( "MMM dd HH:mm:ss" )
                     .withLocale( Locale.ENGLISH );
MonthDay md = MonthDay.parse( "Oct 10 13:10:01" , f );

同样,您可以使用LocalTime类来表示时间。搜索Stack Overflow无数的例子。