Java - DateTimeFormatter - ParseException

Java - DateTimeFormatter - ParseException

我遇到了一个非常奇怪的问题,一小段代码可以在一台机器上运行,而不能在另一台机器上运行。此代码:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
    Map<LocalDate, Double> temperatur = new TreeMap<>();
    for (LocalDate currentDate = LocalDate.parse("2014-jan-01", formatter); currentDate.getYear() < 2015; currentDate = currentDate.plusDays(1))
    {
        String date = currentDate.toString();
        int stringIndex = (data.indexOf(date));
        String tempString = data.substring((stringIndex + 31), (stringIndex + 35));
        if(tempString.contains(";"))
            tempString = tempString.substring(0, 3);
        double temp = Double.parseDouble(tempString);
        temperatur.put(currentDate, temp);
    }

给我例外:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2014-jan-01' could not be parsed at index 5
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDate.parse(Unknown Source)
    at main.SMHITest.getValues(SMHITest.java:50)
    at main.DataCollectionBuilder.addToResult(DataCollectionBuilder.java:46)
    at main.DataCollectionBuilder.<init>(DataCollectionBuilder.java:25)
    at main.ClientProgram.main(ClientProgram.java:14)

SMHITest.Java:50 行就像您在 for 循环中猜到的一样。奇怪的是,这段代码在一台电脑上工作正常,但拒绝在家里为我工作。两台机器都运行 Eclipse mars jee,但一台机器(工作的地方)运行 java 1.8.0_112,另一台运行 java 1.8.0_121-b13。但我无法想象这会是问题所在?

由于给定日期“2014 年 1 月 1 日”与格式 yyyy-MMM-dd 不匹配而引发错误。必须是 2014-Jan-01

不确定你在下面想要实现什么,

String tempString = data.substring((stringIndex + 31), (stringIndex + 35));

if(tempString.contains(";"))

因为日期 2014-01-0 不包含“;”或者它的长度为 35 个字符。

使用新的 java.time 以 case-insensitive 方式 解析像“2014-jan-01”这样的字符串的唯一(也是笨拙的)方法]-API如下:

String input = "2014-jan-01";
DateTimeFormatter dtf =
    new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("uuuu-MMM-dd")
    .toFormatter().withLocale(Locale.ENGLISH);
LocalDate date = dtf.parse(input, LocalDate::from);
System.out.println(date); // 2014-01-01