Title here
Summary here
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.
To run the program, save it as Epoch.kt
and use the Kotlin compiler:
In this Kotlin example:
Instant.now()
to get the current time.epochSecond
gives us the seconds since the Unix epoch.toEpochMilli()
gives us the milliseconds since the Unix epoch.nano
gives us the nanoseconds of the second (not since the epoch).Instant
from seconds and nanoseconds using Instant.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.