Epoch in Crystal
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 Crystal.
To run the program:
In Crystal, we use the Time
struct to work with dates and times. The Time.utc
method gives us the current UTC time. We can then use to_unix
, to_unix_ms
, and to_unix_ns
to get the number of seconds, milliseconds, or nanoseconds since the Unix epoch, respectively.
To convert back from Unix time to a Time
object, we use Time.unix
for seconds and Time.unix_ms
for milliseconds. Crystal doesn’t have a built-in method for nanoseconds conversion, so we’ve omitted that in this example.
Next, we’ll look at another time-related task: time parsing and formatting.