Reputation: 74
I have an ISO duration of ‘PT11M1S’ (from the YouTube API). I know it means 11 minutes and 1 second, but is there any way I can convert it automatically in Kotlin into text that makes sense to the user (instead of the ‘PT11M1S’ string)?
Thanks!
Upvotes: 1
Views: 1605
Reputation: 15299
Target: Java 8+
Use java.time
to get a Duration object. There doesn't seem to be a great formatting solution, and the replaceAll
one does not work on Kotlin Strings, so here is a Kotlin equivalent:
fun humanReadableDuration(s: String): String = java.time.Duration.parse(s).toString()
.substring(2).toLowerCase().replace(Regex("[hms](?!\$)")) { "${it.value} " }
fun main() = println(humanReadableDuration("PT11M1S")) // prints "11m 1s"
The Regex adds spaces after h/m/s but NOT if it's the end of the string to avoid a trailing space.
Target: Any
Since you start with a String already you could avoid the Duration object entirely:
fun humanReadableDuration(s: String): String = s.substring(2)
.toLowerCase().replace(Regex("[hms](?!\$)")) { "${it.value} " }
Upvotes: 2