12

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?

Daniele B
  • 19,801
  • 29
  • 115
  • 173

2 Answers2

13

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

gildor
  • 1,789
  • 14
  • 19
  • 1
    This is a great answer, but users should note that windows does not provide a `gettimeofday` in its POSIX implementation as I found when trying to compile for `mingwX64()` and found in this SO answer: https://stackoverflow.com/questions/13894732/compiler-error-possible-ide-errorundefined-reference-to-gettimeofday-error – Tunji_D Apr 03 '22 at 02:03
  • 1
    @Tunji_D Thanks., you're right, I don't have windows to check, but it's indeed a problem on Windows, updated answer to let know about this limitation – gildor Apr 04 '22 at 03:49
12

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

Daniele B
  • 19,801
  • 29
  • 115
  • 173