【发布时间】:2016-02-09 19:04:25
【问题描述】:
我正在尝试使用 java.time 解析以下时间戳字符串 03-feb-2014 13:16:31,但它会引发错误。这是我的代码。
String timestamp = "03-feb-2014 13:16:31";
DateTimeFormatter format;
DateTimeFormatterBuilder formatBuilder = new DateTimeFormatterBuilder();
formatBuilder.parseCaseInsensitive();
formatBuilder.append(DateTimeFormatter.ofPattern("dd-MMM-YYYY HH:mm:ss"));
format = formatBuilder.toFormatter();
LocalDateTime localdatetime = LocalDateTime.parse(timestamp, format);
但我收到以下错误。
Exception in thread "main" java.time.format.DateTimeParseException: Text '03-feb-2014 13:16:31' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=3, MonthOfYear=2, WeekBasedYear[WeekFields[SUNDAY,1]]=2014},ISO resolved to 13:16:31 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at com.target.util.CntrlmProcessor.main(CntrlmProcessor.java:24)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=3, MonthOfYear=2, WeekBasedYear[WeekFields[SUNDAY,1]]=2014},ISO resolved to 13:16:31 of type java.time.format.Parsed
at java.time.LocalDateTime.from(LocalDateTime.java:461)
at java.time.format.Parsed.query(Parsed.java:226)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
从错误看来,库已经能够解析字符串,因为它从时间戳中分离出所有字段,但我似乎缺少了一些东西。
我尝试仅解析时间戳的时间部分,效果很好。
【问题讨论】:
标签: java parsing datetime java-8 java-time