These Ruby examples use Unix seconds for the portable baseline and show milliseconds only where the runtime exposes them naturally. The question to answer before copying a snippet is simple: what unit does the next API expect?
Get the current Unix time
seconds = Time.now.to_i
milliseconds = (Time.now.to_r * 1000).to_i
Convert a timestamp to UTC
instant = Time.at(1_700_000_000).utc
puts instant.iso8601
Production note
Time.at accepts Unix seconds. Call utc before serializing a value that needs a stable representation.
Keep the unit in the field name when a value crosses a boundary: createdAtSeconds and createdAtMs are longer than createdAt, but much less mysterious during an incident.
Frequent questions:
- Q: Does Time.now.to_i return milliseconds?
- A: No. Time.now.to_i returns whole Unix seconds. Use Time.now.to_f if you need fractional seconds or want to derive milliseconds.
- Q: Why call utc before formatting?
- A: utc makes the output independent of the machine's local timezone. That is helpful for logs, API payloads, and test expectations.
- Q: How do I verify a Ruby timestamp?
- A: Use Time.at(seconds).utc.iso8601 and compare the result with the expected UTC moment before writing the value to a job, API, or database.