kaulex
kaulex

Reputation: 3187

String of type mm:ss:SSS to LocalTime Kotlin/Java

I have a time string 03:02:111 which is of pattern mm:ss:SSS. I would like to transform this into a LocalTime object.

mm -> minutes

ss -> seconds

SSS -> mills

Simple example:

val time = "03:02:111"
val formatter = DateTimeFormatter.ofPattern("mm:ss:SSS")
val convertedTime = LocalTime.parse(time, formatter)
print(convertedTime.toString())

I get the following exception:

java.time.format.DateTimeParseException: Text '03:02:111' could not be parsed: Unable to obtain LocalTime from TemporalAccessor: {MicroOfSecond=111000, MilliOfSecond=111, NanoOfSecond=111000000, SecondOfMinute=2, MinuteOfHour=3},ISO of type java.time.format.Parsed

Can someone explain why this is not working? I also checked the pattern twice.

Upvotes: 1

Views: 407

Answers (1)

João Dias
João Dias

Reputation: 17460

The problem is that you have no definition of the hour. This means you have to build a smarter formatter, telling it which hour should be the default:

fun main(args: Array<String>) {
    val time = "03:02:111"
    val formatter = DateTimeFormatterBuilder()
        .appendPattern("mm:ss:SSS")
        .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
        .toFormatter()
    val convertedTime = LocalTime.parse(time, formatter)
    print(convertedTime.toString())
}

Of course, this will only work as long as the minutes are smaller than 60. If you don't have this guarantee, then you would need another approach.

Upvotes: 3

Related Questions