Java8 LocalDateTime parsing error

2019-04-11 17:35发布

I am trying to parse the following timestamp string 03-feb-2014 13:16:31 using java.time but it is throwing an error. Here is my code.

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);

But I am getting the following error.

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)

From the error it looks like the library has been able to parse the string as it separated out all the fields from the timestamp, but there seems to be something that I am missing.

I tried to parse just the time part of the timestamp alone and that is working just fine.

1条回答
萌系小妹纸
2楼-- · 2019-04-11 18:12

If you use yyyy instead of YYYY in your pattern, the code you've given works. YYYY is "week-based year" which would normally only be used if you're also specifying week number and day-of-week (e.g. a pattern of YYYY-ww-EEE). This is pretty rare.

Note that even just "year" has yyyy and uuuu - yyyy is "year of era" (which is always non-negative - and always positive in the Gregorian calendar) whereas uuuu is a sort of "eraless year" - for example, 5BCE is -4 as an eraless year. If you don't need to deal with dates before the common era (or dates in other calendar systems) you probably don't need to worry about this.

I would also suggest rewriting your code as:

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

... just for simplicity.

查看更多
登录 后发表回答