9

我有一个 Kotlin 多平台项目,我想在共享代码中获取当前的 unixtime。

你如何在 Kotlin 标准库中做到这一点?

4

2 回答 2

9

可以使用实验性 Kotlin 日期时间库,目前版本为 0.1.0

val nowUnixtime = Clock.System.now().epochSeconds

更多信息: https ://github.com/Kotlin/kotlinx-datetime

于 2020-10-07T19:37:23.687 回答
7

如果您已经使用 kotlinx-datetime,或者计划将更多用于其他日期/时间功能,那么使用 kotlinx-datetime 是一个不错的选择。但是,如果您的应用程序/库唯一需要的是 epochSeconds,我认为添加对 kotlinx-datetime 的依赖关系有点过头了。

相反,声明自己的epochMillis()函数并为每个平台实现它很简单:

// for common
expect fun epochMillis(): Long

// for jvm
actual fun epochMillis(): Long = System.currentTimeMillis()

// for js
actual fun epochMillis(): Long = Date.now().toLong()

// for native it depends on target platform
// but posix can be used on any posix-compatible native targets
actual fun epochMillis(): Long = memScoped {
    val timeVal = alloc<timeval>()
    gettimeofday(timeVal.ptr, null)
    (timeVal.tv_sec * 1000) + (timeVal.tv_usec / 1000)
}


于 2020-10-08T02:27:20.973 回答