Java的Duration有a truncate function。
Duration d = myDuration.truncatedTo(ChronoUnit.SECONDS);
字符串
第一个月
返回截断为指定单位的此Duration的副本。
截断持续时间将返回原始值的副本,其中概念字段小于设置为零的指定单位。例如,以MINUTES
为单位进行截断将四舍五入到最接近的分钟,将秒和纳秒设置为零。
然而,Kotlin对Duration有一个不同的实现,它没有类似的截断方法。
我希望能够将Duration除以或乘以某个数字,然后(使用扩展函数)删除任何小于我提供的时间单位。
import kotlin.time.*
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.minutes
fun main() {
val duration = 10.days + 5.hours + 33.minutes
println(duration)
val divided = duration / 100.001
println(divided)
val truncatedToSeconds = divided.truncate(DurationUnit.SECONDS)
println(truncatedToSeconds) // expect: 2h 27m 19s
val truncatedToMinutes = divided.truncate(DurationUnit.MINUTES)
println(truncatedToMinutes) // expect: 2h 27m
val truncatedToHours = divided.truncate(DurationUnit.HOURS)
println(truncatedToHours) // expect: 2h
}
fun Duration.truncate(unit: DurationUnit): Duration {
/// ...
return this
}
型
2条答案
按热度按时间pxq42qpu1#
一种选择是将其转换为
Long
,然后使用所需的单位:字符串
yebdmbv42#
这是一个纯Kotlin截断函数。
它使用
Duration.toComponents()
来获取持续时间的组成部分。然后,它将每个值转换回Duration
,具体取决于它是否等于或大于请求的DurationUnit
。字符串
备注:
nanoseconds
is documented as being less than1_000_000_000
(1秒),因此无需将其转换为秒。nanoseconds
值首先转换为持续时间(nanoseconds.nanoseconds
),然后四舍五入到微秒(inWholeMicroseconds
),然后转换为持续时间(.microseconds
)。使用相同的过程将纳秒四舍五入到毫秒。示例
下面是一个使用示例,演示了
truncate()
函数应用于使用不同时间单位的持续时间。每次截断都会删除小于指定单位的所有时间单位。的数据
Run in Kotlin Playground的