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?
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?
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
Copyright © 2021 Jogjafile Inc.
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:Note: Windows Posix implementation doesn't have gettimeofday so it will not compile on MinGW target