Ruby Snippets

Ruby Unix Timestamp Snippets

Ruby examples for getting Unix seconds, deriving milliseconds, converting timestamps to Time objects, formatting UTC output, and parsing date strings.

Current Unix timestamp (seconds)
Time.now.to_i
Current Unix timestamp (milliseconds)
(Time.now.to_f * 1000).round
Time from Unix timestamp
Time.at(1700000000)
Time in specific timezone
require "time"
Time.at(1700000000).utc.strftime("%Y-%m-%d %H:%M:%S")

# With tzinfo gem:
require "tzinfo"
tz = TZInfo::Timezone.get("America/New_York")
tz.utc_to_local(Time.at(1700000000).utc)
Formatted string
Time.at(1700000000).strftime("%Y-%m-%d %H:%M:%S")
Timestamp from Time
require "time"
Time.parse("2023-11-15T06:13:20Z").to_i

Ruby timestamp basics

Ruby's Time.now.to_i returns Unix seconds. Use Time.now.to_f when you need fractional seconds or want to calculate milliseconds for APIs that expect JavaScript-style timestamps.

Converting and formatting Ruby Time

Use Time.at(timestamp) to create a Time object from Unix seconds. Call utc before formatting when you need stable output that does not depend on the machine's local timezone.

Ruby production notes

Ruby's Time methods are concise, but timezone defaults can vary between laptops, servers, and background workers. Keep persisted timestamps in Unix seconds or UTC strings, then apply the application timezone at the presentation layer. When parsing user input, include the offset or timezone so daylight saving rules are not guessed incorrectly.

  • Use Time.now.to_i for Unix seconds
  • Use (Time.now.to_f * 1000).round for millisecond values
  • Use Time.at(seconds).utc for stable UTC output
  • Use Time.parse only with strings that include a timezone or offset

FAQ

Does Time.now.to_i return milliseconds?
No. Time.now.to_i returns whole Unix seconds. Use Time.now.to_f if you need fractional seconds or want to derive milliseconds.
Why call utc before formatting?
utc makes the output independent of the machine's local timezone. That is helpful for logs, API payloads, and test expectations.
How do I verify a Ruby timestamp?
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.