解析为 YearMonth

Parsing into YearMonth

我想将两个单独的字符串 "1982""SEP" 解析为一个 java.time.YearMonth 对象。

java.time.YearMonth.parse("1978 SEP", java.time.format.DateTimeFormatter.ofPattern("yyyy LLL"))

给我

java.time.format.DateTimeParseException: Text '1978 SEP' could not be parsed at index 5
  at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
  at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
  at java.time.YearMonth.parse(YearMonth.java:295)

这里有3个(可能是2个)问题:

  • 您的语言环境不是英语,因此 "SEP" 不能理解为九月。这可以通过将英语语言环境设置为格式化程序来解决。
  • DateTimeFormatter 默认情况下区分大小写,因此您需要构建一个不区分大小写的格式化程序。
  • 您不应使用 "L" 标记,而应使用 "M":请参阅

以下将起作用:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("yyyy MMM")
                                    .toFormatter(Locale.ENGLISH);
System.out.println(YearMonth.parse("1978 SEP", formatter));

我试过你的代码,如果你看一下java如何打印它使用的日期 月份首字母大写(在我的执行中) 只需键入 Sep 而不是 sep,并在字符串模式中使用 MMM 而不是 LLL。

在使用字符串模式解析日期之前,请查看它们如何打印在系统输出上,然后相应地编写您的字符串模式。

此示例仅适用于语言环境英语,在语言环境意大利语中,字符串日期模式不同,因此如果您更改语言环境,我建议您修改解析器

尝试{

            java.time.YearMonth.parse("1978 Sep", java.time.format.DateTimeFormatter.ofPattern("yyyy MMM" ));

        }

        catch(DateTimeParseException e)

        {

            e.printStackTrace();

        }

}