我有一个Kotlin多平台项目,我想在共享代码中获得当前的unixtime。
在Kotlin标准库中如何做到这一点?
发布于 2020-10-08 03:37:24
可以使用实验性的Kotlin日期时间库,当前版本为0.1.0
val nowUnixtime = Clock.System.now().epochSeconds
发布于 2020-10-08 10:27:21
如果您已经在使用kotlinx-datetime,或者计划对其他日期/时间特性使用更多,那么使用kotlinx-datetime是一个很好的选择。但是,如果您的应用程序/libray唯一需要的是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)
}https://stackoverflow.com/questions/64251153
复制相似问题