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.

import java.time.Instant

object Epoch extends App {
  // 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.getEpochSecond)
  println(now.toEpochMilli)
  println(now.getNano)

  // You can also convert integer seconds or nanoseconds since the epoch into the corresponding Instant
  println(Instant.ofEpochSecond(now.getEpochSecond))
  println(Instant.ofEpochSecond(0, now.getNano))
}

To run the program:

$ scala Epoch.scala
2023-05-15T12:34:56.789Z
1684153696
1684153696789
789000000
2023-05-15T12:34:56Z
1970-01-01T00:00:00.789Z

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 epoch
  • toEpochMilli: Returns the number of milliseconds since the Unix epoch
  • getNano: 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.