【问题标题】:Java8 LocalDateTime parsing errorJava8 LocalDateTime 解析错误
【发布时间】: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


    【解决方案1】:

    如果您在模式中使用yyyy 而不是YYYY,则您提供的代码有效。 YYYY 是“基于周的年份”,通常仅在您还指定周数和星期几时使用(例如,YYYY-ww-EEE 的模式)。这非常罕见。

    请注意,即使只是“年份”也有 yyyyuuuu - yyyy 是“时代的年份”(它始终是非负数 - 在公历中始终是正数),而 uuuu 是某种“永恒的年份” - 例如,5BCE 是 -4 作为永恒的年份。如果您不需要处理普通纪元之前的日期(或其他日历系统中的日期),您可能不需要担心这一点。

    我还建议将您的代码重写为:

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

    ...只是为了简单。

    【讨论】:

    • 这是一个很好的解释!另外,我已经采纳了你的建议。 :)