Search code examples
javadatetimetimelocaltime

How to parse different time formats


I have different time formats in string (from videoplayer counter). For example:

03:45 -> 3 munutes, 45 seconds
1:03:45 -> 1 hour, 3 munutes, 45 seconds
123:03:45 -> 123 hours, 3 munutes, 45 seconds

How can I parse all this formats with LocalTime lib?

If I using such code:

LocalTime.parse(time, DateTimeFormatter.ofPattern("[H[H]:]mm:ss"));

It works fine for "1:03:45" or "11:03:45", but for "03:55" I have exception

java.time.format.DateTimeParseException: Text '03:55' could not be parsed at index 5

Solution

  • There are more possibilities. I would probably go for modifying the time string to conform with the syntax accepted by Duration.parse.

        String[] timeStrings = { "03:45", "1:03:45", "123:03:45" };
        for (String timeString : timeStrings) {
            String modifiedString = timeString.replaceFirst("^(\\d+):(\\d{2}):(\\d{2})$", "PT$1H$2M$3S")
                    .replaceFirst("^(\\d+):(\\d{2})$", "PT$1M$2S");
            System.out.println("Duration: " + Duration.parse(modifiedString));
        }
    

    Output is:

    Duration: PT3M45S
    Duration: PT1H3M45S
    Duration: PT123H3M45S
    

    The case of hours, minutes and seconds (two colons) is handled by the first call to replaceFirst, which in turn removes both colons and makes sure that the second replaceFirst doesn’t replace anything. In the case of just one colon (minutes and seconds), the first replaceFirst cannot replcae anything and passes the string unchanged to the second replaceFirst call, which in turn transforms to the ISO 8601 format accepted by Duration.parse.

    You need the Duration class for two reasons: (1) If I understand correctly, your time string denotes a duration, so using LocalTime is incorrect and will confuse those maintaining your code after you. (2) The maximum value of a LocalTime is 23:59:59.999999999, so it will never accept 123:03:45.