Epoch in Ruby

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 Ruby.

require 'time'

# Use Time.now to get the current time
now = Time.now
puts now

# Get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds
puts now.to_i
puts (now.to_f * 1000).to_i
puts (now.to_f * 1_000_000_000).to_i

# You can also convert integer seconds or nanoseconds since the epoch into the corresponding Time
puts Time.at(now.to_i)
puts Time.at(now.to_f)

To run the program:

$ ruby epoch.rb
2023-05-15 10:30:45 +0000
1684145445
1684145445000
1684145445000000000
2023-05-15 10:30:45 +0000
2023-05-15 10:30:45 +0000

In Ruby, we use the Time class to work with dates and times. The Time.now method gives us the current time. To get the number of seconds since the Unix epoch, we use the to_i method, which returns the integer representation of the time (seconds since epoch).

For milliseconds and nanoseconds, we convert the time to a float using to_f, multiply by 1000 or 1_000_000_000 respectively, and then convert back to an integer.

To convert from seconds or nanoseconds back to a Time object, we use Time.at. This method can accept either an integer (interpreted as seconds) or a float (interpreted as seconds with fractional part for sub-second precision).

Next, we’ll look at another time-related task: time parsing and formatting.