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.

require "time"

# Use Time.utc with to_unix, to_unix_ms, or to_unix_ns
# to get elapsed time since the Unix epoch in seconds,
# milliseconds or nanoseconds, respectively.
now = Time.utc
puts now

puts now.to_unix
puts now.to_unix_ms
puts now.to_unix_ns

# You can also convert integer seconds or nanoseconds
# since the epoch into the corresponding Time.
puts Time.unix(now.to_unix)
puts Time.unix_ms(now.to_unix_ms)

To run the program:

$ crystal epoch.cr
2023-06-13 12:34:56 UTC
1686661496
1686661496000
1686661496000000000
2023-06-13 12:34:56 UTC
2023-06-13 12:34:56 UTC

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.