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.
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.789Z
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.