Java DateTimeFormatter未按预期进行分析

Java DateTimeFormatter未按预期进行分析,java,Java,我尝试了DateTimeFormatter将输入日期解析为dd/MM/yyyy。我使用了下面的代码 java.time.format.DateTimeFormatter无法分析日期 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy").withResolverStyle(ResolverStyle.STRICT); try {

我尝试了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;
    }
输入:2018年4月30日


闰年也是失败的。

问题正在使用。WithResolversTyle ResolverStyle.STRICT要求使用年份模式uuuu而不是yyyy,即年份而不是纪年

这里基本上有两个选项,其中一个是使用代码示例中显示的ResolverStyle:

显式使用ResolverStyle.STRICT⇒ 只解析u年 使用默认的解析器样式⇒ 将解析年代y或年代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 因此,两个DateTimeFormatter都解析相同的字符串,但是没有显式附加ResolverStyle的一个将根据上下文默认使用ResolverStyle.SMART

当然,带有u年的模式也将由ResolverStyle.SMART解析,所以

这也是一种选择


可以很好地解释纪年和年份之间的差异。

使模式dd/MM/UUU。。。或者保留ResolderStyle,但如果需要ResolderStyle.STRICT,则必须使用u年而不是y年。@deHaar-或者使用DateTimeFormatterBuilder.parseDefaulting提供默认纪元。@OleV.V。这应该是另一个答案。。。或者添加到现有的问题中,但我没有时间了。@deHaar我想我找到了一个更适合原始问题的方法。我添加了它并编写了它。
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);
}
DateTimeFormatter.ofPattern("dd/MM/uuuu");