我的时间以毫秒为单位:
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
Run Code Online (Sandbox Code Playgroud)
。我需要将其转换为秒表格式(HH:MM:SS)。我知道有很多选择。但最现代、最简单的方法是什么?
首先也是最重要的是,您不应该使用System.currentTimeMillis()经过的时间。该时钟适用于挂钟时间,并且会受到漂移或闰秒调整的影响,这可能会严重扰乱您的测量结果。
更好用的时钟是System.nanoTime(). 但在 Kotlin 中,如果您想测量经过的时间,则不需要显式调用它。您可以使用不错的实用程序,例如measureNanoTime,或者实验性的measureTime,它直接返回Duration您可以格式化的值:
val durationNanos = measureNanoTime {
// run the code to measure
}
val duration = measureTime {
// run the code to measure
}
Run Code Online (Sandbox Code Playgroud)
Duration如果您不想使用measureTime并且仍然只有毫秒或纳秒数,则可以Duration使用 的扩展属性之一将它们转换为 a Duration.Companion:
import kotlin.time.Duration.Companion.milliseconds
val durationMillis: Long = 1000L // got from somewhere
val duration: Duration = durationMillis.milliseconds
Run Code Online (Sandbox Code Playgroud)
然而,这非常尴尬,这就是这些扩展被弃用一段时间的原因。它们被恢复是因为它们很适合与数字文字一起使用,但它们不太适合与变量名称一起使用。相反,您可以使用Long.toDuration():
import kotlin.time.*
val durationMillis = 1000L // got from somewhere
val duration = durationMillis.toDuration(DurationUnit.MILLISECONDS)
Run Code Online (Sandbox Code Playgroud)
Duration如果您只想要一个漂亮的视觉格式,请注意,kotlin.time.Duration由于其良好的toString实现,该类型已经可以很好地打印:
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
}
Run Code Online (Sandbox Code Playgroud)
在操场上看到它:https://pl.kotl.in/YUT6FZA0l
如果您确实想要您要求的格式,您也可以使用toComponents@Can_of_awe 提到的:
// example duration, built from extensions on number literals
val duration = 4.minutes + 67.seconds + 230.milliseconds
val durationString = duration.toComponents { hours, minutes, seconds, _ ->
"%02d:%02d:%02d".format(hours, minutes, seconds)
}
println(durationString) // prints 00:05:07
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1875 次 |
| 最近记录: |