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.nowuses the process zone; in Rails useTime.currentsoTime.zoneis respected. require "time"is needed beforeTime.parseandiso8601— they are not loaded by default.
Rules that apply in every language
- Store UTC, display local. Keep the instant in UTC everywhere in your system and convert only at the point a human reads it.
- Name the unit in the identifier.
expires_at_msrather thanexpires_atcosts nothing and prevents the single most common timestamp bug. - Never trust a client clock. Stamp anything security-relevant on the server. See the note on clock skew.
- 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
- Python float seconds
- JavaScript integer milliseconds
- PHP integer seconds
- Java integer milliseconds
- Go integer seconds and nanoseconds
- TypeScript integer milliseconds
- C# ticks (100 ns)
- Rust seconds + nanoseconds
- SQL varies by engine
- Bash integer seconds
- C++ chrono duration
- Swift float seconds
- Kotlin integer milliseconds
- C time_t seconds
- Perl integer seconds
- Dart integer milliseconds
- PowerShell .NET DateTimeOffset
- Scala integer milliseconds
- R float seconds
- Excel days since 1899-12-30
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.