使用STRICT解析器样式时出现DateTimeParseException问题

时间:2016-12-12 14:56:19

标签: java-8 java-time

我正在尝试使用以下模式解析日期字符串:yyMMddSTRICT解析程序,如下所示:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat).withResolverStyle(ResolverStyle.STRICT);
LocalDate.parse(expiryDate, formatter);

我得到以下DateTimeParseException

  

java.time.format.DateTimeParseException:文本'160501'不能   解析:无法从TemporalAccessor获取LocalDate:   {YearOfEra = 2016,MonthOfYear = 5,DayOfMonth = 1},ISO类型   java.time.format.Parsed

当我切换到默认的解析风格时,即ResolverStyle.SMART,它允许的日期为2月30日。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:8)

严格的解析器需要一个时代与YearOfEra一起使用。将您的模式更改为使用“u”而不是“y”,它将起作用,即。 “uuMMdd”。

答案 1 :(得分:1)

尽管JodaStephen很好地解释了异常的原因并给出了一个好的解决方案(使用uu而不是yy),但我提供了其他两种可能的解决方案:

  1. 您可能不希望使用的显而易见的方法:将解析器样式保留为SMART(默认设置)。换句话说,要么完全忽略.withResolverStyle(ResolverStyle.STRICT),要么将其更改为.withResolverStyle(ResolverStyle.SMART)
  2. 提供默认时代。

对于第二个选项,这里是一个代码示例:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("yyMMdd")
            .parseDefaulting(ChronoField.ERA, 1)
            .toFormatter()
            .withResolverStyle(ResolverStyle.STRICT);

    String expiryDate = "160501";
    LocalDate result = LocalDate.parse(expiryDate, formatter);
    
    System.out.println(result);

输出为:

2016-05-01

与在格式模式中使用uu相比,最后一种解决方案可能会有所不同:

  1. 它允许我们使用给定的格式模式,在这种模式下我们无法控制是否使用模式字母uy
  2. 使用模式字母y时,如果字符串中包含负的年份,则将失败并出现异常。根据您的情况和要求,这可能是理想的还是不可接受的。