xref: /aosp_15_r20/external/android_onboarding/java/com/android/onboarding/utils/time.kt (revision c625018464ae97c56936c82b1b617e11aa899faa)

<lambda>null1 package com.android.onboarding.utils
2 
3 import java.time.Duration
4 import java.time.Instant
5 import java.time.LocalTime
6 import java.time.ZoneId
7 import java.time.format.DateTimeFormatter
8 import kotlin.math.absoluteValue
9 import kotlin.time.toKotlinDuration
10 
11 /** Get the [LocalTime] of this [Instant] under UTC timezone. */
12 val Instant.time: LocalTime
13   get() = LocalTime.ofInstant(this, ZoneId.of("UTC"))
14 
15 /** Returns the time component string of this [Instant] under UTC timezone. */
16 val Instant.timeString: String
17   get() = time.format(DateTimeFormatter.ISO_LOCAL_TIME)
18 
19 /** Formats a given duration into a human-readable string `[-]HH:mm:ss.sss`. */
20 fun Duration.format(): String =
21   toKotlinDuration().toComponents { hours, minutes, seconds, nanoseconds ->
22     val negative = hours < 0 || minOf(minutes, seconds, nanoseconds) < 0
23     val ms = (nanoseconds / 1e6).toInt().absoluteValue
24     val s = seconds.absoluteValue
25     val m = minutes.absoluteValue
26     val h = hours.absoluteValue
27 
28     val chunks = mutableListOf<String>()
29     if (h > 0) chunks.add("${h}h")
30     if (m > 0 || h > 0) chunks.add("${m.toString().padStart(2)}min")
31     chunks.add("${s.toString().padStart(2)}.${ms.toString().padStart(3, '0')}s")
32     (if (negative) "-" else "") + chunks.joinToString(separator = " ").trim()
33   }
34 
35 /** Returns the [Duration] between [start] and `this` [Instant]. */
minusnull36 operator fun Instant.minus(start: Instant): Duration = Duration.between(start, this)
37 
38 inline val Number.seconds: Duration
39   get() = Duration.ofSeconds(toLong())
40 inline val Number.minutes: Duration
41   get() = Duration.ofMinutes(toLong())
42 inline val Number.hours: Duration
43   get() = Duration.ofHours(toLong())
44