Epoch in Groovy

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 Groovy.

import java.time.Instant

// Use Instant.now() to get the current timestamp
def 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)

To run the program, save it as epoch.groovy and use the groovy command:

$ groovy epoch.groovy
2023-05-10T12:34:56.789Z
1683722096
1683722096789
789000000
2023-05-10T12:34:56Z
1970-01-01T00:00:00.789Z

Use Instant.now() to get the current timestamp. You can then use epochSecond, toEpochMilli(), or nano to get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds, respectively.

You can also convert integer seconds or nanoseconds since the epoch into the corresponding Instant using Instant.ofEpochSecond().

Next, we’ll look at another time-related task: time parsing and formatting.