Unix timestamps in Ruby
Ruby's core Time class handles Unix time directly. Time.at reads a timestamp and to_i writes one.
Get the current Unix timestamp
Time.now.to_i # seconds
Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) # milliseconds (Integer)
Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond) # nanoseconds
Convert a Unix timestamp to a date
Time.at(1700000000).utc
# => 2023-11-14 22:13:20 UTC
Time.at(1700000000, 123, :millisecond).utc
# => 2023-11-14 22:13:20.123 UTC
Time.at(1700000000, in: "+05:30")
# => 2023-11-15 03:43:20 +0530
Convert a date to a Unix timestamp
Time.utc(2026, 11, 14, 10, 0, 0).to_i # => 1794650400
Time.new(2026, 11, 14, 15, 30, 0, "+05:30").to_i # => 1794650400
(Time.now.to_r * 1000).to_i # milliseconds
Timezones
# Core Ruby understands fixed offsets. For IANA zones use the tzinfo gem:
require "tzinfo"
tz = TZInfo::Timezone.get("America/New_York")
tz.to_local(Time.at(1700000000))
# => 2023-11-14 17:13:20 -0500
Common mistakes
Time.at(n)returns local time. Add.utcor passin:to be explicit.Time.parse("2026-11-14 10:00")without an offset is read in the machine's zone.- Rails'
Time.zoneandTime.currentfollow the app's configured zone, not the server's. PlainTime.nowignores it.
Complete example
require "time" # iso8601 needs this before Ruby 3.4
now = Time.now.to_i
puts "Now: #{now}"
t = Time.at(1700000000).utc
puts "1700000000 = #{t.iso8601}"
puts "Back to epoch: #{Time.utc(2023, 11, 14, 22, 13, 20).to_i}"
Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).