Epoch in Scala
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 Scala.
To run the program:
In Scala, we use the java.time.Instant
class to work with timestamps. The Instant.now()
method gives us the current time. We can then use various methods to get the time in different units:
getEpochSecond
: Returns the number of seconds since the Unix epochtoEpochMilli
: Returns the number of milliseconds since the Unix epochgetNano
: Returns the nanosecond-of-second
We can also create Instant
objects from epoch seconds or nanoseconds using Instant.ofEpochSecond
.
Note that Scala, being a JVM language, uses Java’s time API, which is slightly different from the Go time package. The concepts are similar, but the method names and exact behaviors might differ slightly.
Next, we’ll look at another time-related task: time parsing and formatting.