这是我的密码:
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd HH:mm:ss");
LocalDateTime timeStamp = LocalDateTime.parse(string, formatter);这就导致了这一异常:
java.time.format.DateTimeParseException:文本“10月10日13: 10 :01”无法解析:无法从TemporalAccessor获得LocalDateTime:{MonthOfYear=10,DayOfMonth=10},ISO解析为java.time.format.Parsed类型的13:10:01
使用Java 1.8.0_31。
我确实环顾四周,发现了许多类似的问题,但这些问题并不完全符合这个问题,在这里提出的解决方案不适用于此:
这里相同问题的原因是使用没有时间部分的LocalDateTime。正如你从期望中看到的,这里不是这样的。
我不像在这例子中那样使用基于周的年份。
最后,与这里不同,我使用的是LocalDateTime,所以时区不应该是一个问题。但是,由于它被认为是一个DateTimeFormatter中的bug,我尝试将格式化程序传递为'formatter.withZone(ZoneId.systemDefault())‘(建议的解决方法),这导致了同样的异常。
发布于 2016-10-11 15:10:03
一个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())发布于 2016-10-11 20:26:20
亚述人的回答是正确的,应该被接受。
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类表示一天中的时间。搜索堆栈溢出数不清的例子。
https://stackoverflow.com/questions/39978897
复制相似问题