Reputation: 83
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.
Upvotes: 0
Views: 1828
Reputation:
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)
Upvotes: 1
Reputation: 148
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.
Upvotes: 1