首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析为YearMonth

解析为YearMonth
EN

Stack Overflow用户
提问于 2015-11-13 16:49:33
回答 2查看 3.5K关注 0票数 2

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

代码语言:javascript
复制
java.time.YearMonth.parse("1978 SEP", java.time.format.DateTimeFormatter.ofPattern("yyyy LLL"))

给我

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-13 16:56:07

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

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

下列措施将起作用:

代码语言:javascript
复制
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                    .parseCaseInsensitive()
                                    .appendPattern("yyyy MMM")
                                    .toFormatter(Locale.ENGLISH);
System.out.println(YearMonth.parse("1978 SEP", formatter));
票数 9
EN

Stack Overflow用户

发布于 2015-11-13 17:02:36

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

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

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

尝试{

代码语言:javascript
复制
            java.time.YearMonth.parse("1978 Sep", java.time.format.DateTimeFormatter.ofPattern("yyyy MMM" ));

        }

        catch(DateTimeParseException e)

        {

            e.printStackTrace();

        }

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33697795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档