kotlinx 是一組不是 Kotlin 標準庫一部分,但非常實用的擴展項目集合。其中,kotlinx-datetime
是一個跨平臺的 Kotlin 時間日期處理庫。
如何在項目中使用該庫
Gradle 項目中
在 repositories
塊中添加 Maven Central 倉庫:
repositories {mavenCentral()
}
說明:告訴 Gradle 在 Maven Central 倉庫中查找依賴。
然后在 dependencies
塊中添加依賴(以版本 0.4.0 為例):
dependencies {implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.4.0")
}
說明:將 kotlinx-datetime 庫作為實現依賴加入項目。
Maven 項目中
添加如下依賴:
<dependency><groupId>org.jetbrains.kotlinx</groupId><artifactId>kotlinx-datetime-jvm</artifactId><version>0.4.0</version>
</dependency>
說明:Maven 中的依賴聲明,版本號同樣為 0.4.0。
在源文件中導入時間處理包:
import kotlinx.datetime.*
說明:引入庫中所有時間相關的類和函數。
Instant(瞬時點)介紹
Instant
表示時間線上某個具體的時刻,常用于比較兩個時間點或存儲時間戳。
創建 Instant 對象
創建 Instant 的實例非常簡單
你可以使用該now()
方法獲取當前日期和時間,如下所示:
import kotlinx.datetime.Clockfun main() {val currentInstant = Clock.System.now()println(currentInstant) // 例如輸出:2023-07-24T13:39:16.310148200Z
}
說明:Clock.System.now()
獲取當前 UTC 時間的 Instant
。
轉換為毫秒時間戳
如果你需要以毫秒為單位的時間,可以使用.toEpochMilliseconds()
val currentInstantInMillisec = currentInstant.toEpochMilliseconds()
說明:toEpochMilliseconds()
返回當前時間點自 Unix 紀元(1970-01-01T00:00:00Z)以來的毫秒數。
從毫秒時間戳創建 Instant
或者fromEpochMilliseconds()
基于毫秒創建實例
val specificInstant = Instant.fromEpochMilliseconds(currentInstantInMillisec)
說明:通過毫秒時間戳反向創建 Instant
對象。
Instant 的加減操作
可以使用 plus()
和 minus()
給 Instant
加上或減去一定的時間段(Duration
):
import kotlin.time.Durationval futureInstant = currentInstant.plus(Duration.parse("6h")) // 當前時間加6小時
val pastInstant = currentInstant.minus(Duration.parse("24h")) // 當前時間減24小時
Instant 和其他日期時間類型的轉換
即時可以輕松轉換為其他日期和時間類型,反之亦然
val zonedDateTime = currentInstant.toLocalDateTime(TimeZone.currentSystemDefault())
val backToInstant = zonedDateTime.toInstant(TimeZone.currentSystemDefault())
說明:Instant 總是 UTC 時間,轉換為 LocalDateTime
需要指定時區,反向轉換時同理。
Instant 在實際場景中的應用
-
事件日志記錄
-
任務管理中時間點比較
-
用戶界面更新時間顯示
使用 Instant 時的注意事項
-
Instant
始終表示 UTC 時間,不含時區信息。 -
顯示本地時間需先轉換成對應時區的日期時間類型,例如 LocalDateTime 或 ZonedDateTime。
TimeZone 類介紹
用于表示時區信息。
-
TimeZone.currentSystemDefault()
:獲取系統默認時區 -
TimeZone.UTC
:UTC 時區(ISO 8601 中的 “Z”)
val tz1 = TimeZone.currentSystemDefault()
val tz2 = TimeZone.UTC
println(tz2) // 輸出 Z
其他時區可以用 TimeZone.of()
方法傳入時區字符串,如偏移量或區域名,可從tz數據庫"Europe/Rome"中找到有效的時區名稱:
val tz3 = TimeZone.of("Europe/Paris") // 巴黎時區
val tz4 = TimeZone.of("UTC+2") // UTC+2 時區
無效參數會拋出 IllegalTimeZoneException
。
DateTimePeriod 類
用來表示兩個 Instant
之間的時間差,并且將這個差異拆分成日期和時間的組成部分。你可以通過 years
、months
、days
、hours
、minutes
、seconds
和 nanoseconds
等屬性來訪問這些時間差。
獲取兩個 Instant
之間差值:
val period: DateTimePeriod = instant1.periodUntil(instant2, TimeZone.UTC)
println(period) // 輸出 ISO 8601 格式,如 P9M12DT4H
使用 periodUntil(other: Instant, timeZone: TimeZone)
成員函數,可以獲得兩個 Instant
之間的時間差。其中 other
是另一個 Instant
,timeZone
是時區。
println(period)
// 輸出:P9M12DT4Hprintln("Months: ${period.months} Days: ${period.days} Hours: ${period.hours}")
// 輸出:Months: 9 Days: 12 Hours: 4
P9M12DT4H
表示一個 ISO 8601 時間段:9個月,12天,4小時。period.months
返回 9,表示 9 個月。period.days
返回 12,表示 12 天。period.hours
返回 4,表示 4 小時。
DateTimePeriod 的另一個重要用處 — 作為時間偏移量加減 Instant
可以用 Instant.plus()
給一個 Instant
添加一個時間段,或者用 Instant.minus()
減去一個時間段。
val after = instant.plus(period, TimeZone.UTC) // 加時間段
val before = instant.minus(period, TimeZone.UTC) // 減時間段
period
表示 1 年 1 個月 1 天 1 小時 1 分鐘 1 秒以及 123,456,789 納秒的時間段。instant.plus(period, TimeZone.UTC)
會返回加上該時間段之后的新時間。instant.minus(period, TimeZone.UTC)
會返回減去該時間段之前的時間。
Duration 和 DateTimePeriod 的區別
-
Duration
(kotlin.time)表示固定長度的時間量(天、小時、分鐘等),通常用于時間差的絕對值。 -
DateTimePeriod
(kotlinx)表示以年月日等日歷單位劃分的時間段,更適合人類理解和日期計算。
示例:
val instant1 = Instant.parse("2100-01-01T00:00:00Z")
val instant2 = Instant.parse("2105-07-09T15:23:40Z")val duration = instant2 - instant1
println(duration) // 2015d 15h 23m 40s
println(duration.inWholeDays) // 2015val period = instant1.periodUntil(instant2, TimeZone.UTC)
println(period) // P5Y6M8DT15H23M40S
println(period.days) // 8
Duration
是表示精確的時間間隔(以秒和納秒為單位),如總共多少天、多少小時。DateTimePeriod
表示日歷時間段,可以按年、月、日、小時、分鐘、秒拆分。- 例如,
Duration
的輸出顯示總計了 2015 天 15 小時 23 分鐘 40 秒,而DateTimePeriod
顯示了 5 年 6 個月 8 天 15 小時 23 分鐘 40 秒。
總結
本文介紹了 kotlinx-datetime
庫中的 Instant
、TimeZone
、DateTimePeriod
等核心類的使用方法,幫助你正確創建、轉換和操作時間點及時間段。這個庫還支持更多功能,比如日期和時間的本地化,方便跨平臺日期時間處理。