Java8 LocalDateTime解析错误

mah*_*der 3 java datetime parsing java-8 java-time

我试图解析以下时间戳字符串03-feb-2014 13:16:31使用java.time但它抛出一个错误.这是我的代码.

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);
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误.

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)
Run Code Online (Sandbox Code Playgroud)

从错误看起来,库已经能够解析字符串,因为它从时间戳中分离出所有字段,但似乎有一些我缺少的东西.

我试图仅解析时间戳的时间部分而且工作得很好.

Jon*_*eet 12

如果您使用yyyy而不是YYYY在您的模式中,您提供的代码可以使用.YYYY是"基于周的年份",通常只有在您还指定周数和星期几(例如模式YYYY-ww-EEE)时才会使用.这非常罕见.

请注意,即使只是"年"已经- yyyy并且uuuu- yyyy是"时代之年"(它总是非负面的 - 并且在公历中始终是正面的)而是uuuu一种"无年代" - 例如,5BCE是-4一个没有时间的一年.如果您不需要在共同时代之前处理日期(或其他日历系统中的日期),您可能不需要担心这一点.

我还建议将代码重写为:

DateTimeFormatter format = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern("dd-MMM-yyyy HH:mm:ss")
    .toFormatter();
Run Code Online (Sandbox Code Playgroud)

......只是为了简单.