Epoch in Kotlin
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Kotlin.
import java.time.Instant
fun main() {
// Use Instant.now() to get the current time
val now = Instant.now()
println(now)
// Get elapsed time since the Unix epoch in seconds,
// milliseconds or nanoseconds
println(now.epochSecond)
println(now.toEpochMilli())
println(now.nano)
// You can also convert integer seconds or nanoseconds
// since the epoch into the corresponding Instant
println(Instant.ofEpochSecond(now.epochSecond))
println(Instant.ofEpochSecond(0, now.nano.toLong()))
}To run the program, save it as Epoch.kt and use the Kotlin compiler:
$ kotlinc Epoch.kt -include-runtime -d Epoch.jar
$ java -jar Epoch.jar
2023-06-04T12:34:56.789Z
1685883296
1685883296789
789000000
2023-06-04T12:34:56Z
1970-01-01T00:00:00.789ZIn this Kotlin example:
- We use
Instant.now()to get the current time. epochSecondgives us the seconds since the Unix epoch.toEpochMilli()gives us the milliseconds since the Unix epoch.nanogives us the nanoseconds of the second (not since the epoch).- We can create an
Instantfrom seconds and nanoseconds usingInstant.ofEpochSecond().
Note that Kotlin/Java’s Instant handles time slightly differently from Go’s time.Time. In particular, it doesn’t have a direct equivalent to Go’s UnixNano(). Instead, we use toEpochMilli() for milliseconds and nano for nanoseconds within the second.
Next, we’ll look at another time-related task: time parsing and formatting.
Comments powered by Disqus