Time in Scala
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 an Instant
.
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
, and equals
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:
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.