如何在 Kotlin 标准库(多平台)上获取当前的 unixtime

Dan*_*e B 5 datetime standard-library unix-timestamp kotlin current-time

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

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

gil*_*dor 12

如果您已经使用 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 MOST (see below) of 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)
}


Run Code Online (Sandbox Code Playgroud)

注意:Windows Posix 实现没有 gettimeofday,因此它不会在 MinGW 目标上编译


Dan*_*e B 6

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

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

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