Skip to content

Timestamp Converter — Ruby source

Convert Unix epoch timestamps to human-readable dates and back. See seconds, milliseconds, ISO 8601, UTC, local and relative time at once.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# timestamp — Unix epoch (seconds & milliseconds) <-> ISO 8601 / UTC / local strings and relative time ("3 hr ago" / "in 2 day"). Ruby port of src/tools/TimestampConverter.tsx — same logic as this dir's typescript.ts; fromISO parsing omitted for the 80-line budget (see typescript.ts / python.py).

# Human relative time: bucket |now - t| into sec/min/hr/day/month/yr with
# the island's 60s / 60m / 24h / 30d / 365d thresholds, round to the
# nearest whole unit, then sign it ("ago" past / "in" future).
def relative_time(ms, now_ms)
  diff = ms - now_ms
  a = diff.abs / 1000.0
  n, unit =
    if    a < 60           then [a.round, 'sec']
    elsif a < 3_600        then [(a / 60).round, 'min']
    elsif a < 86_400       then [(a / 3_600).round, 'hr']
    elsif a < 86_400 * 30  then [(a / 86_400).round, 'day']
    elsif a < 86_400 * 365 then [(a / (86_400 * 30)).round, 'month']
    else                        [(a / (86_400 * 365)).round, 'yr']
    end
  diff.negative? ? "#{n} #{unit} ago" : "in #{n} #{unit}"
end

# Render every form the tool exposes from "now" — the island's row table:
# epoch (s), epoch (ms), ISO 8601, UTC string, local string, relative time.
# %3N is milliseconds; #utc + the RFC-ish shape mirrors toUTCString().
t = Time.now
ms = (t.to_f * 1000).to_i
puts "Epoch (s):  #{ms / 1000}"
puts "Epoch (ms): #{ms}"
puts "ISO 8601:  #{t.utc.strftime('%Y-%m-%dT%H:%M:%S.%3NZ')}"
puts "UTC:       #{t.utc.strftime('%a, %d %b %Y %H:%M:%S GMT')}"
puts "Local:     #{t.strftime('%Y-%m-%d %H:%M:%S')}"
puts "Relative:  #{relative_time(ms, ms)}"
puts "In 3 hr:   #{relative_time(ms + 3 * 3_600_000, ms)}"

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →