DateTimeFormatter parseBest() 给出“无法在索引 8 处解析”异常

DateTimeFormatter parseBest() gives ' could not be parsed at index 8' exception

我对 parseBest 方法的工作原理有点困惑。 我有一个格式化程序模式,我正在使用 parseBest 方法解析日期,如下所示:

    DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm:ss[Z]]");
    parseMyDate(parser, "2016-12-07");
    parseMyDate(parser, "2016-12-07T15:31:12");
    parseMyDate(parser, "2016-12-07T15:31:12-0500");
    parseMyDate(parser, "2016-12-07Hello");

    public static void parseMyDate(DateTimeFormatter formatter, String parseText) {
    try {
      TemporalAccessor ta = formatter.parseBest(parseText, 
                                                OffsetDateTime::from,
                                                LocalDateTime::from, 
                                                LocalDate::from);
      if (ta instanceof OffsetDateTime) {
        OffsetDateTime odt = OffsetDateTime.from(ta);
        System.out.println("OffsetDateTime: " + odt);
      } else if (ta instanceof LocalDateTime) {
        LocalDateTime ldt = LocalDateTime.from(ta);
        System.out.println("LocalDateTime: " + ldt);
      } else if (ta instanceof LocalDate) {
        LocalDate ld = LocalDate.from(ta);
        System.out.println("LocalDate: " + ld);
      } else {
        System.out.println("Parsing returned: " + ta);
      }
    } catch (DateTimeParseException e) {
      System.out.println("Here in Exception : "+e.getMessage());
      //e.printStackTrace();
    }
  }

但是对于所有的方法调用,我得到了如下相同的异常:

java.time.format.DateTimeParseException: Text '2016-12-07Hello' could not be parsed at index 8 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parseBest(DateTimeFormatter.java:1897) at com.my.j8.DataTime.parseStr(DataTime.java:164) at com.my.j8.DataTime.main(DataTime.java:158)

我尝试按如下方式更改模式: DateTimeFormatter 解析器 = DateTimeFormatter.ofPattern("yyyy-MM- dd");

但还是没有运气。有什么建议吗?

您的模式中 -dd 之前有一个 space,因此您的 none 日期与该模式匹配 - 匹配必须准确。

"yyyy-MM-dd['T'HH:mm:ss[Z]]" 的模式(没有 space)适用于您的前 3 个模式。

最后一个模式仍然失败,因为模式不匹配 Hello - 模式必须匹配整个输入字符串。