Unix timestamps in Ruby

Get the current epoch time and convert between timestamps and dates in Ruby. Every snippet below is copy-ready.

// note

Time.now.to_i is seconds; Time.at builds a Time from epoch.

now.rb · current timestamp
now    = Time.now.to_i
now_ms = (Time.now.to_f * 1000).to_i
timestamp → date
ts = 1700000000
dt = Time.at(ts).utc
puts dt.iso8601  # 2023-11-14T22:13:20Z
date → timestamp
require 'time'
ts = Time.iso8601('2023-11-14T22:13:20Z').to_i
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://docs.ruby-lang.org/en/master/Time.html

advertisement