Epoch in Karel
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 Java.
To run the program:
In Java, we use the Instant
class from the java.time
package to work with time instants on the timeline. The Instant.now()
method gives us the current instant, which we can then use to get the epoch time in various formats.
The getEpochSecond()
method returns the number of seconds from the epoch, toEpochMilli()
returns milliseconds, and getNano()
returns the nanosecond adjustment to the second.
We can also create an Instant
from epoch seconds or nanoseconds using the Instant.ofEpochSecond()
method.
Next, we’ll look at another time-related task: time parsing and formatting.