Unix Timestamp in Ruby

Ruby's Time class handles epochs directly. In Rails, ActiveSupport::TimeWithZone adds proper zone handling on top.

Need to convert one value rather than write code? Use the interactive converter — it handles every unit and time zone without leaving your browser.

Current Unix timestamp

Time.now.to_i          # 1710050400        seconds
Time.now.to_f          # 1710050400.123456 float seconds
(Time.now.to_f * 1000).to_i    # milliseconds

Timestamp to date

ts = 1710050400

Time.at(ts).utc.iso8601        # "2024-03-10T06:00:00Z"
Time.at(ts).getlocal("+05:30").strftime("%Y-%m-%d %H:%M:%S %Z")

require "tzinfo"
TZInfo::Timezone.get("Asia/Kolkata").to_local(Time.at(ts))

Date to timestamp

require "time"

Time.utc(2024, 3, 10, 6, 0, 0).to_i        # 1710050400
Time.parse("2024-03-10T06:00:00Z").to_i
Time.iso8601("2024-03-10T06:00:00Z").to_i

Rails

Time.current.to_i                       # respects Time.zone
Time.zone.at(1710050400)
Time.zone.parse("2024-03-10 11:30:00")

# config/application.rb
# config.time_zone = "UTC"

Pitfalls specific to Ruby

  • Plain Time.now uses the process zone; in Rails use Time.current so Time.zone is respected.
  • require "time" is needed before Time.parse and iso8601 — they are not loaded by default.

Rules that apply in every language

  1. Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
  2. Name the unit in the identifier. expires_at_ms rather than expires_at costs nothing and prevents the single most common timestamp bug.
  3. Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
  4. Use 64-bit time. Anything still storing seconds in a signed 32-bit field breaks in January 2038 — see the Year 2038 problem.

The same task in other languages

Frequently asked questions

How do I get the current Unix timestamp in Ruby?

Use the snippet in the "Current Unix timestamp" section above. Ruby works in float seconds natively, so converting to another unit is a multiplication or an integer division away.

How do I convert a Unix timestamp to a date in Ruby?

The "Timestamp to date" snippet above shows the idiomatic approach, including how to render the result in a specific time zone rather than whatever zone the machine happens to be set to.

Does Ruby handle time zones and daylight saving correctly?

Yes, provided you pass an explicit zone rather than relying on the system default. The gotchas listed on this page cover the specific ways Ruby makes that easy to get wrong.