【问题标题】:Java DateTimeFormatter is not parsing as expected [duplicate]Java DateTimeFormatter 未按预期解析 [重复]
【发布时间】:2020-12-21 16:36:43
【问题描述】:

我尝试使用 DateTimeFormatter 将输入日期解析为 dd/MM/yyyy。我用过下面的代码

java.time.format.DateTimeFormatter 无法解析日期

  DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT);
    
       
            try {
                LocalDate.parse(dateField, dateFormatter);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        
        return true;
    }

输入:30/04/2018

Error:Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=4, YearOfEra=2018, DayOfMonth=30},ISO of type java.time.format.Parsed

闰年也是失败的。

【问题讨论】:

  • 制作模式"dd/MM/uuuu"... 或者留下ResolverStyle,但如果你想要ResolverStyle.STRICT,你将不得不使用年份(u)而不是年份(y)。
  • @deHaar — 或使用 DateTimeFormatterBuilder.parseDefaulting() 提供默认时代。
  • @OleV.V.那应该作为另一个答案添加...或添加到现有答案之一,但我没有时间了。
  • @deHaar 我想我找到了更适合原始问题的方法。我已经添加并写了a new answer here

标签: java


【解决方案1】:

您基本上有两个选择(这里,一个是使用您在代码示例中显示的ResolverStyle):

  • 明确使用ResolverStyle.STRICT ⇒ 仅解析年份 u
  • 使用默认的 ResolverStyleyear-of-era yyear u 将被解析

下面的例子展示了代码的不同之处:

public static void main(String[] args) {
    String date = "30/04/2018";
    // first formatter with year-of-era but no resolver style
    DateTimeFormatter dtfY = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    // second one with year and a strict resolver style
    DateTimeFormatter dtfU = DateTimeFormatter.ofPattern("dd/MM/uuuu")
                                                .withResolverStyle(ResolverStyle.STRICT);
    // parse
    LocalDate localDateU = LocalDate.parse(date, dtfU);
    LocalDate localDateY = LocalDate.parse(date, dtfY);
    // print results
    System.out.println(localDateU);
    System.out.println(localDateY);
}

输出是

2018-04-30
2018-04-30

所以DateTimeFormatters 都解析相同的String,但没有明确附加ResolverStyle 的将根据JavaDocs of DateTimeFormatter 默认使用ResolverStyle.SMART

当然,带有 year (u) 的模式也会被 ResolverStyle.SMART 解析,所以

DateTimeFormatter.ofPattern("dd/MM/uuuu");

也是一种选择。

year-of-erayear 之间的区别很好的解释可以在in this post找到。

【讨论】:

    【解决方案2】:

    问题在于使用.withResolverStyle(ResolverStyle.STRICT) 需要使用年份模式uuuu 而不是yyyy(即“年”而不是“时代”)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2020-08-19
      • 2021-11-05
      • 1970-01-01
      • 2021-01-13
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多