0

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!

gidds
  • 16,558
  • 2
  • 19
  • 26
AWE
  • 64
  • 4
  • 14
  • 2
    What format would you like it in?  Something like “11 minutes and 1 second” (i.e. in English text)?  Does it need to be localisable? – gidds Nov 23 '20 at 22:01
  • Are you targeting at least Java 8? – xjcl Nov 23 '20 at 23:14

1 Answers1

1

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} " }
xjcl
  • 12,848
  • 6
  • 67
  • 89