Unix timestamps in Ruby
Everything Ruby needs for Unix timestamps: the current epoch time in seconds and milliseconds, timestamp-to-date and date-to-timestamp conversion, and ISO 8601 parsing. Ruby's Time is pleasant, with one setup note: iso8601 lives in the standard library's time extension, so scripts need require "time" (Rails loads it for you). There's a live converter at the bottom for checking any value the snippets produce.
Get the current Unix timestamp
seconds = Time.now.to_i # 1700000000
millis = (Time.now.to_f * 1000).to_i # 1700000000000Convert a timestamp to a Time
t = Time.at(1700000000).utc
# 2023-11-14 22:13:20 UTCTime.at renders in the process's local zone; chain .utc for the UTC reading.
Convert a Time to a timestamp
seconds = t.to_i
millis = (t.to_f * 1000).to_iParse and format ISO 8601
require "time"
t = Time.iso8601("2023-11-14T22:13:20Z")
s = t.utc.iso8601 # "2023-11-14T22:13:20Z"Prefer Time.iso8601 over Time.parse for machine input; parse guesses at ambiguous formats.
Check a value
Detected: Unix timestamp (seconds)/t/1700000000
Your timezone
UTC · GMT+00:00 · UTC
Tue, Nov 14, 2023, 10:13:20 PM
Common formats
UTC
Tue, Nov 14, 2023, 10:13:20 PM
ISO 8601
2023-11-14T22:13:20.000Z
Unix (seconds)
1700000000
Unix (millis)
1700000000000
Relative
…
Common questions
- Time, Date, or DateTime?
- Time for anything timestamp-shaped. Date for pure calendar dates. DateTime is discouraged by Ruby's own docs; it's slower and its arithmetic differs subtly.
- How does Rails change this?
- Rails adds Time.zone (Time.zone.now, Time.zone.at(ts)) which respects the app's configured zone rather than the server's. In a Rails app, use Time.zone consistently and let ActiveRecord store UTC.
- Why does Time.parse give surprising results?
- It accepts almost anything and guesses, "11/14/2023" vs "14/11/2023" ambiguity included. For API input, use Time.iso8601, which fails loudly on anything nonstandard.