Skip to content
Advertisement

java.time.format.DateTimeParseException, and I do not know how to solve it

I am trying to get data about some athletes from a csv file, then create athlete objects that are going to be stored in a list. The problem is that I get an error when I try to parse the time they’ve got as LocalDateTime.This is the error I get:

Exception in thread “main” java.time.format.DateTimeParseException: Text ’30:27′ could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MinuteOfHour=30, MicroOfSecond=0, MilliOfSecond=0, SecondOfMinute=27, NanoOfSecond=0},ISO of type java.time.format.Parsed

This is the code:

public static void addAthletes() {
    try (BufferedReader br = new BufferedReader(
            new FileReader("C:\Users\****\******\**********\src\main\java\ro\sci\tema10_ski_biathlon_standings\standings.csv"))) {
        String line = null;
        while ((line = br.readLine()) != null) {
            athleteList.add(getAthleteFromCsvLine(line));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static Athlete getAthleteFromCsvLine(String line) {

    String[] athleteAttributes = line.split(",");

    if (athleteAttributes.length != 7) {
        throw new IllegalArgumentException();
    }

    int athleteNumber = Integer.parseInt(athleteAttributes[0].trim());
    LocalDateTime skiTimeResults = LocalDateTime.parse(athleteAttributes[3].trim(),
            DateTimeFormatter.ofPattern("mm:ss"));

     return new Athlete(
             athleteNumber,
             athleteAttributes[1],
             athleteAttributes[2],
             skiTimeResults,
             athleteAttributes[4],
             athleteAttributes[5],
             athleteAttributes[6]
     );

}

Please help me overcome this

Advertisement

Answer

Well, LocalDateTime expects a date component to be present, and a valid time component. Your 30:27 text contains neither: obviously, 30:27 as a wall clock time does not exist.

It seems you are looking for a duration here. Use Duration. Note that Duration does not have a method to parse the text 30:27 successfully, so we have to convert it to a ISO period/duration string:

String[] components = athleteAttributes[3].trim().split(":");
String durationStr = String.format("PT%sM%sS", components[0], components[1]);
Duration duration = Duration.parse(durationStr);

Alternatively, you could use

String[] components = athleteAttributes[3].trim().split(":");
int minutes = Integer.parseInt(components[0]);
int seconds = Integer.parseInt(components[1]);
Duration duration = Duration.ofMinutes(minutes).plusSeconds(seconds);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement