How to get current unixtime on Kotlin standard library (multiplatform)

4.8k Views Asked by At

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?

2

There are 2 best solutions below

2
On

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

0
On

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