Search code examples
javaexceptionlocaldate

Java - DateTimeFormatter - ParseException


I have this really strange problem of a small snippet of code working on one machine, and not another. This code:

    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);
    }

Gives me the exception:

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)

The SMHITest.Java:50 line is as you might guess right at the for loop. The strange part is, this piece of code works fine at one computer, but refuses to work for me at home. Both machines runs Eclipse mars jee, but one machine (where its working) runs java 1.8.0_112, and the other one runs java 1.8.0_121-b13. But i cant imagine that would be the problem?


Solution

  • the error is thrown as it given date "2014-jan-01" doesn't match with format yyyy-MMM-dd. It needs to be 2014-Jan-01

    not sure what are you trying to achieve here in the following ,

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

    as date 2014-01-0 doesn't contains ';' or it has 35 characters in length.