Unix timestamps in Ruby

Ruby's Time class stores an instant with nanosecond precision and converts to a timestamp with to_i. Watch which zone a Time is displayed in, and which zone Time.parse assumes.

Current timestamp

Time.now.to_i                                             # e.g. 1763164800     seconds
(Time.now.to_f * 1000).to_i                               # e.g. 1763164800123  milliseconds
Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)   # the same, without a Time object

Timestamp to time

Every example uses 1700000000, which is 14 November 2023 at 22:13:20 UTC, so you can compare the output across languages or check it in the timestamp converter.

require 'time'

t = Time.at(1700000000).utc
t.iso8601                          # "2023-11-14T22:13:20Z"
t.strftime('%Y-%m-%d %H:%M:%S')    # "2023-11-14 22:13:20"

Time.at(1700000000, in: '-05:00').iso8601          # "2023-11-14T17:13:20-05:00"
Time.at(0, 1700000000123, :millisecond).utc.iso8601(3)   # "2023-11-14T22:13:20.123Z"

Time.at returns the instant in the local zone of the machine; .utc switches it to UTC. The in: keyword (Ruby 2.6 and later) takes a UTC offset, and the unit argument (Ruby 2.5 and later) lets you pass milliseconds as the second value. The iso8601 method is added by require 'time'.

Date to timestamp

require 'time'

Time.utc(2023, 11, 14, 22, 13, 20).to_i             # 1700000000
Time.iso8601('2023-11-14T22:13:20Z').to_i           # 1700000000
Time.parse('2023-11-14 22:13:20 UTC').to_i          # 1700000000
Time.new(2023, 11, 14, 17, 13, 20, '-05:00').to_i   # 1700000000

Pitfalls

  • Time.parse without a zone assumes local time, and it guesses at loosely written dates. For input from other systems use Time.iso8601 or Time.strptime, which raise on anything unexpected.
  • Time.new(2023, 11, 14) and Time.local are local; Time.utc is not. The two differ by your UTC offset.
  • to_i truncates the fraction; use to_f or to_r to keep it.
  • In Rails, Time.current and Time.zone.at(ts) follow the application's configured zone, while Time.now follows the server's. The timestamp from to_i is the same from both.

Questions

How do I get the current Unix timestamp in Ruby?

Time.now.to_i gives seconds. For milliseconds use (Time.now.to_f * 1000).to_i.

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

Time.at(timestamp).utc gives a Time in UTC. Call .to_date on it (after require "date") if you only want the calendar day.