当前位置: 首页 > news >正文

Kotlin的datetime库

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 之间的时间差,并且将这个差异拆分成日期和时间的组成部分。你可以通过 yearsmonthsdayshoursminutessecondsnanoseconds 等属性来访问这些时间差。
获取两个 Instant 之间差值:

val period: DateTimePeriod = instant1.periodUntil(instant2, TimeZone.UTC)
println(period) // 输出 ISO 8601 格式,如 P9M12DT4H

使用 periodUntil(other: Instant, timeZone: TimeZone) 成员函数,可以获得两个 Instant 之间的时间差。其中 other 是另一个 InstanttimeZone 是时区。


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 库中的 InstantTimeZoneDateTimePeriod 等核心类的使用方法,帮助你正确创建、转换和操作时间点及时间段。这个库还支持更多功能,比如日期和时间的本地化,方便跨平台日期时间处理。


http://www.xdnf.cn/news/1204489.html

相关文章:

  • Linux内核驱动开发核心问题全解
  • 四、计算机组成原理——第4章:指令系统
  • 基于Spring Boot+Vue的吉他社团系统设计和实现(协同过滤算法)
  • 飞鹤困局:增长神话的裂痕
  • 分布式数据库中的“分布式连接”(Distributed Joins)
  • 轻资产革命:连合直租如何用DaaS模式重塑企业资产逻辑
  • 阿里云 【免费试用】MCP 赋能可视化 OLAP 智能体应用
  • 网络安全第14集
  • React与Rudex的合奏
  • KubeSphere理论及实战
  • ros2的package.xml和rosdep
  • 正则表达式 速查速记
  • haproxy原理及实验演示(实现服务器集群的负载均衡)
  • ubuntu资源共享samba 安装与配置 mac/windows共享ubuntu文件资源
  • 无人机喷洒系统技术要点与难点解析
  • AR眼镜:工业4.0时代高风险作业的安全守护者
  • 【WRF-Chem教程第七期】闪电-NOx 参数化方案详解
  • 自学嵌入式 day36 数据库
  • 前段面试题新版
  • 【华为机试】5. 最长回文子串
  • 数据结构——图(二、图的存储和基本操作)
  • 数据结构 | 队列:从概念到实战
  • Rust 最短路径、Tide、Partial、Yew、Leptos、数独实践案例
  • Nginx HTTP 反向代理负载均衡实验
  • Docker笔记(基本命令、挂载本地gpu、Dockerfile文件配置、数据挂载、docker换源)
  • Ettus USRP X410/X440 运行 ADC 自校准
  • easyexcel填充方式导出-合并单元格并设置边框
  • 解构远程智能系统的视频能力链:从RTSP|RTMP协议接入到Unity3D头显呈现全流程指南
  • MVSNet系列网络概述
  • 把振动数据转成音频并播放