【问题标题】:Parsing into YearMonth解析成年月
【发布时间】:2015-11-13 16:49:33
【问题描述】:

我想将两个单独的字符串 "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)

【问题讨论】:

    标签: java java-time


    【解决方案1】:

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

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

    以下将起作用:

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

    【讨论】:

      【解决方案2】:

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

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

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

      试试{

                  java.time.YearMonth.parse("1978 Sep", java.time.format.DateTimeFormatter.ofPattern("yyyy MMM" ));
      
              }
      
              catch(DateTimeParseException e)
      
              {
      
                  e.printStackTrace();
      
              }
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-28
        • 2019-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多