Unix Timestamps in Ruby and Rails
Ruby's Time class handles Unix timestamps natively. Rails adds ActiveSupport::TimeWithZone for robust timezone handling. Here are the essential patterns.
Get the current Unix timestamp
Time.now.to_i returns the current epoch in seconds. Use Time.now.to_f for float precision.
# Seconds since epoch (integer)
Time.now.to_i # => 1700000000
# Seconds with fractional precision
Time.now.to_f # => 1700000000.123456
# Rails: UTC-aware current time
Time.current.to_i # => 1700000000
AdSense — In-Article Banner
Convert a Unix timestamp to a Time object
Time.at() converts epoch seconds to a Time object. Chain .utc to ensure UTC output.
# From seconds
t = Time.at(1700000000)
puts t.utc # => 2023-11-14 22:13:20 UTC
puts t.iso8601 # => "2023-11-14T22:13:20+00:00"
# From milliseconds
t = Time.at(1700000000000 / 1000.0)
puts t.utc.iso8601
Rails: timezone-aware timestamps
In Rails, always use Time.current instead of Time.now to respect the app's configured timezone.
# Convert epoch to Rails TimeWithZone
ts = 1700000000
time = Time.zone.at(ts)
puts time # => Tue, 14 Nov 2023 22:13:20 UTC +00:00
# ActiveRecord: created_at returns TimeWithZone automatically
user = User.find(1)
puts user.created_at.to_i # epoch seconds
puts user.created_at.iso8601
AdSense — In-Article Banner