问题描述
我有一个Kotlin跨平台项目,我想在共享代码中获取当前的unixtime。
您如何在Kotlin标准库中做到这一点?
解决方法
可以使用实验性的Kotlin日期时间库, 当前版本为0.1.0
val nowUnixtime = Clock.System.now().epochSeconds
更多信息在这里: https://github.com/Kotlin/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)
}