Reputation: 20412
I have a Kotlin multiplatform project, and I would like to get the current unixtime in the shared code.
How do you do that in the Kotlin standard library?
Upvotes: 16
Views: 6602
Reputation: 1894
Usage of kotlinx-datetime is a good choice if you already use it, or plan to use more for other date/time features. But if the only thing which is required for your app/libray is epochSeconds, I think it's an overkill to add a dependency on kotlinx-datetime.
Instead declaring own epochMillis()
function and implement it for every platform is simple enough:
// 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)
}
Note: Windows Posix implementation doesn't have gettimeofday so it will not compile on MinGW target
Upvotes: 16
Reputation: 20412
It's possible to use the experimental Kotlin datetime library, currently at version 0.1.0
val nowUnixtime = Clock.System.now().epochSeconds
More info here: https://github.com/Kotlin/kotlinx-datetime
Upvotes: 18