Kotlin - 时间 Duration

时间:2024-04-14 20:34:14

一、概念

用于表示时间度量,简化了时间单位的换算、计算时间差、操作间隔、比较等场景。

二、使用

2.1 创建

2.1.1 Number -> Duration

扩展函数适用于 Int、Long、Double。Duration 可以是正、负、零、正无穷大或负无穷大。

nanoseconds public inline val Int.nanoseconds get() = toDuration(DurationUnit.NANOSECONDS)
microseconds public inline val Int.microseconds get() = toDuration(DurationUnit.MICROSECONDS)
milliseconds public inline val Int.milliseconds get() = toDuration(DurationUnit.MILLISECONDS)
seconds public inline val Int.seconds get() = toDuration(DurationUnit.SECONDS)
minutes public inline val Int.minutes get() = toDuration(DurationUnit.MINUTES)
hours public inline val Int.hours get() = toDuration(DurationUnit.HOURS)
days public inline val Int.days get() = toDuration(DurationUnit.DAYS)
val tenSeconds: Duration = 10.seconds   //打印:10s
val sixMinutes: Duration = 6.minutes   //打印:6m
val negativeOneNanoseconds: Duration = (-1).seconds   //打印:-1ns
val negativeInfiniteDays: Duration = Double.NEGATIVE_INFINITY.days   //打印:-Infinity

2.1.2 String -> Duration 

2.2 转换

2.2.1 Duration -> Number

一个要传单位,一个直接使用。

toXXX(DurationUnit)

public fun toInt(unit: DurationUnit): Int        //使用注意精度不够

public fun toLong(unit: DurationUnit): Long

public fun toDouble(unit: DurationUnit): Double

.inWholeXXX

public val inWholeNanoseconds: Long

public val inWholeMicroseconds: Long

public val inWholeMilliseconds: Long

public val inWholeSeconds: Long

public val inWholeMinutes: Long

public val inWholeHours: Long

public val inWholeDays: Long

val before = 30.minutes
val after1 = before.toLong(DurationUnit.SECONDS) //打印:1800
val after2 = before.inWholeSeconds  //打印:1800

2.2.2 Duration -> String

2.3 四则运算

无论是什么单位都可以相互运算。

val twelveHours = 12.hours
val oneDay = 1.days
val thirtyMilliseconds = 30.milliseconds
val fiveMilliseconds = 5.milliseconds
println(oneDay + twelveHours)   //打印:1d 12h
println(oneDay + thirtyMilliseconds)   //打印:1d 0h 0m 0.03s
println(thirtyMilliseconds / fiveMilliseconds) //  打印:6.0

2.4 逻辑运算

val oneHour = 1.hours
val sixtyMinutes = 60.minutes
val twoHouts = 2.hours
println(oneHour == sixtyMinutes)   //打印:true
println(oneHour > twoHouts)   //打印:false

2.5 解构

分别获取不同单位上的数值,不是整个转换成该单位的数值。

val time = 548341869.seconds
println(time + 0.seconds)   //6346d 13h 11m 9s
time.toComponents { seconds, nanoseconds ->  }
time.toComponents { minutes, seconds, nanoseconds ->  }
time.toComponents { hours, minutes, seconds, nanoseconds ->  }
time.toComponents { days, hours, minutes, seconds, nanoseconds ->
    println(days)   //6346
    println(hours)  //13
    println(minutes)    //11
    println(seconds)    //9
    println(nanoseconds)    //0
}