0

I got a API which gives me data for start and end time like this: "tstart":"80000","tend":"160000"

Do you have a easy way to format it to time like 08:00 and 16:00 with Kotlin?

Thank you.

Jade
  • 83
  • 9
  • Possible duplicate of [How to convert milliseconds to "hh:mm:ss" format?](https://stackoverflow.com/questions/9027317/how-to-convert-milliseconds-to-hhmmss-format) – CodeMatrix Aug 13 '18 at 22:08

2 Answers2

1

First, it controls the length of the values, if they have 5 positions it adds 0 in the first position.

Then use DateTimeFormatter.ofPattern ("HH: mm: ss") (look this https://developer.android.com/reference/java/time/format/DateTimeFormatter)

Another option and simpler is to format the chain, adding a ":" every two positions since you will always have a value of 6 characters.

Jsperk
  • 124
  • 1
  • 11
1

In your question you did not mention if in the string contains minutes.
If not, you can use the following function:

fun getTime(s: String): String {
    var timeInt = 0
    try {
        timeInt = s.split(":")[1].replace("\"", "").toInt()
    } catch (e: Exception) { }
    timeInt /= 10000
    val timeStr = timeInt.toString().padStart(2, '0') + ":00"
    return timeStr
}

and use it like this:

val start =  "\"tstart\":\"80000\""
val end = "\"tend\":\"160000\""
val formattedStart = getTime(start)
val formattedEnd =  getTime(end)