【问题标题】:Java YearMonth will not parse, but only on my computer? [duplicate]Java YearMonth 不会解析,只能在我的电脑上解析? [复制]
【发布时间】:2021-10-19 01:36:37
【问题描述】:

我一直在做一个需要我以这种方式解析字符串的项目 我已经分离出了一直抛出错误的小部分,


import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class TestingYearMonth {

    public static void main(String[] args) {
        
           YearMonth yearMonth = YearMonth.parse("Feb-17", DateTimeFormatter.ofPattern("MMM-yy"));
            System.out.println(yearMonth.getMonth() + " " + yearMonth.getYear());
        
    }
}

我的老师运行完全相同的代码,它返回的输出没有问题。但是当我运行它时,我收到以下错误

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Feb-17' could not be parsed at index 0
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.YearMonth.parse(YearMonth.java:295)
    at com.ethanbradley.assignment6.TestingYearMonth.main(TestingYearMonth.java:10)

我们检查过,我的 jdk 没问题(jdk 11,amazon coretto 版本) 我真的不明白为什么这不起作用,请帮助哦聪明的互联网人....

【问题讨论】:

  • 你机器的Locale是什么?
  • 试试.ofPattern("MMM-yy", Locale.US)
  • 哇,添加 Locale.US 有效,但似乎没有其他 Locale,你知道为什么吗?
  • @EthanLTB 不同的语言环境对月份值的生成/解析方式有不同的要求,例如,有些可能是FEB(不包括非英语语言)

标签: java parsing java-11 java-time


【解决方案1】:

指定Locale

您的 JVM 的默认区域设置可能不是将“Feb”识别为 2 月份的区域设置。

指定Locale 以确定用于解析月份名称的人类语言和文化规范。

Locale locale = Locale.US ; 
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM-yy" , locale ) ;
YearMonth yearMonth = YearMonth.parse( "Feb-17" , f );

看到这个code run live at IdeOne.com

ISO 8601

使用本地化文本进行数据交换是不明智的。我建议您向您的数据发布者宣传 ISO 8601 标准格式,以便将日期时间值交换为文本。

年月的标准格式是 YYYY-MM。示例:2017-02

java.time 类默认使用 ISO 8601 格式。

YearMonth.parse( "2017-02" )

【讨论】:

  • (1) 关于 ISO 8601 的注释很好也很重要。 (2) 我更喜欢u 而不是y。 (3) 致 OP:您可以从this answer 了解更多关于LocaleDateTimeFormatter 的重要性。
  • 太好了,谢谢!
  • 你成功了。 :-)
猜你喜欢
  • 2017-12-31
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2013-10-01
  • 2016-11-24
  • 2012-04-07
  • 2014-03-13
相关资源
最近更新 更多