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.
To run the program:
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.