Unix Timestamp in Ruby

Ruby's Time class has built-in Unix timestamp support. Time.now.to_i gives you seconds; multiply by 1000 for milliseconds. Rails adds extra helpers via ActiveSupport.

Ad

Code Examples

Current timestamp (seconds)

Time.now.to_i

Returns the current Unix timestamp in seconds as an Integer. Clean and idiomatic.

Current timestamp (milliseconds)

(Time.now.to_f * 1000).to_i

to_f returns seconds as a Float with sub-second precision. Multiply by 1000 and convert to Integer for milliseconds.

Using Time.at to convert

Time.at(1708560000).utc
# => 2024-02-22 00:00:00 UTC

Convert a Unix timestamp back to a Time object. Call .utc to display in UTC rather than local time.

Rails / ActiveSupport

Time.current.to_i         # UTC-aware current time
Time.zone.now.to_i        # zone-aware current time

In Rails, prefer Time.current over Time.now — it respects config.time_zone. Both respond to to_i for Unix timestamps.

Parse ISO 8601 date to timestamp

require "time"
Time.parse("2024-06-15T12:00:00Z").to_i

Require 'time' for Time.parse. It handles ISO 8601, HTTP dates, and many other formats.

Note

Ruby's to_i truncates to seconds (not milliseconds). This is consistent with Python and Go. In Rails apps, always use Time.current or Time.zone.now instead of Time.now to avoid local-time bugs in multi-timezone apps.

Ad

Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.

← Open the converter