Time in Scala
import java.time.{Duration, Instant, LocalDateTime, ZoneId}
import java.time.temporal.ChronoUnit
object TimeExample {
def main(args: Array[String]): Unit = {
val p = println _
// We'll start by getting the current time.
val now = Instant.now()
p(now)
// You can build a time by providing the year, month, day, etc.
// Times are always associated with a ZoneId (time zone).
val then = LocalDateTime.of(2009, 11, 17, 20, 34, 58, 651387237)
.atZone(ZoneId.of("UTC"))
.toInstant
p(then)
// You can extract the various components of the time value as expected.
p(then.atZone(ZoneId.of("UTC")).getYear)
p(then.atZone(ZoneId.of("UTC")).getMonth)
p(then.atZone(ZoneId.of("UTC")).getDayOfMonth)
p(then.atZone(ZoneId.of("UTC")).getHour)
p(then.atZone(ZoneId.of("UTC")).getMinute)
p(then.atZone(ZoneId.of("UTC")).getSecond)
p(then.getNano)
p(then.atZone(ZoneId.of("UTC")).getZone)
// The Monday-Sunday Weekday is also available.
p(then.atZone(ZoneId.of("UTC")).getDayOfWeek)
// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
p(then.isBefore(now))
p(then.isAfter(now))
p(then.equals(now))
// The Duration class represents the interval between two times.
val diff = Duration.between(then, now)
p(diff)
// We can compute the length of the duration in various units.
p(diff.toHours)
p(diff.toMinutes)
p(diff.getSeconds)
p(diff.toNanos)
// You can use plus to advance a time by a given duration,
// or with minus to move backwards by a duration.
p(then.plus(diff))
p(then.minus(diff))
}
}
This Scala code demonstrates working with times and durations. Here’s a breakdown of what it does:
We start by getting the current time using
Instant.now()
.We create a specific time using
LocalDateTime.of()
and convert it to anInstant
.We extract various components of the time, such as year, month, day, etc.
We demonstrate how to get the day of the week.
We compare two times using
isBefore
,isAfter
, andequals
methods.We calculate the duration between two times using
Duration.between()
.We show how to get the duration in different units like hours, minutes, seconds, and nanoseconds.
Finally, we demonstrate how to add or subtract a duration from a time.
To run this program, save it in a file named TimeExample.scala
and use the Scala compiler:
$ scalac TimeExample.scala
$ scala TimeExample
This will compile and run the Scala program, displaying various time and duration calculations.
Next, we’ll look at the related idea of time relative to the Unix epoch.