Home > Enterprise >  How to convert milliseconds to Stopwatch format in Kotlin? (HH:MM:SS)
How to convert milliseconds to Stopwatch format in Kotlin? (HH:MM:SS)

Time:06-09

I have time in milliseconds which i'm getting by:

    val past = System.currentTimeMillis()
    val future = System.currentTimeMillis()   1000L
    
    // getting duration every second. imagine working stopwatch here
    val duration = future - past
    
    // Imconvert duration to HH:MM:SS

. I need to convert it to stopwatch format (HH:MM:SS). I know there is a lot of options. But what is the most modern and easiest way to do it?

CodePudding user response:

A more Kotlin-style straightforward way of doing this:

val durationString = duration.milliseconds.toComponents { hours, minutes, seconds, _ ->
    "d:d:d".format(hours, minutes, seconds)
}

Where the .milliseconds extension is from import kotlin.time.Duration.Companion.milliseconds

CodePudding user response:

First and foremost, you should not use System.currentTimeMillis() for elapsed time. This clock is meant for wallclock time and is subject to drifting or leap second adjustments that can mess up your measurements significantly.

A better clock to use would be System.nanoTime(). But in Kotlin you don't need to call it explicitly if you want to measure elapsed time. You can use nice utilities like measureNanoTime, or the experimental measureTime which directly returns a Duration that you can format.

If you don't want to use measureTime and still have just a number of milliseconds, you can convert them to a Duration by using the Duration.Companion.milliseconds extension property (but that's more appropriate for number literals) or Long.toDuration():

import kotlin.time.*

val millisFromSomewhere = 1000L
val duration = millisFromSomewhere.toDuration(DurationUnit.MILLISECONDS)

If you just want a nice visual format, note that the kotlin.time.Duration type is already printed nicely:

import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Duration.Companion.milliseconds

fun main() {
    val duration = 4.minutes   67.seconds   230.milliseconds
    println(duration) // prints 5m 7.23s
}

See it in the playground: https://pl.kotl.in/YUT6FZA0l

If you really want the format you're asking for, you may also use toComponents as @Can_of_awe mentioned:

val duration = 4.minutes   67.seconds   230.milliseconds
val durationString = duration.toComponents { hours, minutes, seconds, _ ->
    "d:d:d".format(hours, minutes, seconds)
}
println(durationString) // prints 00:05:07
  • Related