Parsing a Duration String in Kotlin

后端 未结 3 1889
终归单人心
终归单人心 2021-01-06 10:06

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

3条回答
  •  庸人自扰
    2021-01-06 10:23

    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)
    

提交回复
热议问题