I\'m working on a Android application and I need to parse a duration string of this form \"00:00:00.000\" (Ex: \"00:00:38.47\" or \"00:03:27.11\").
My final goal is
The method getSeconds() that you use returns only the seconds of the parsed time and also it is deprecated.
If you can't use LocalTime.parse() in your Android app because it requires API level 26, then split the time string and parse it by multiplying each part with the appropriate factor:
val timeString = "00:01:08.83"
val factors = arrayOf(3600.0, 60.0, 1.0, 0.01)
var value = 0.0
timeString.replace(".", ":").split(":").forEachIndexed { i, s -> value += factors[i] * s.toDouble() }
println(value)
will print:
68.83
You could also create an extension function:
fun String.toSeconds(): Double {
val factors = arrayOf(3600.0, 60.0, 1.0, 0.01)
var value = 0.0
this.replace(".", ":").split(":").forEachIndexed { i, s -> value += factors[i] * s.toDouble() }
return value
}
and use it:
val timeString = "00:01:08.83"
val seconds = timeString.toSeconds()
println(seconds)