How to Get current Unix timestamp or milliseconds since epoch Ruby Programming| Ruby on Rails by Example

This article shows how to obtain the current timestamp, Unix timestamp, or epoch timestamp in the Ruby programming language. We’ll make use of Time class.

The epoch timestamp, often known as the Unix timestamp, is a long integer in milliseconds that represents the time of day. It’s the number of milliseconds that have elapsed since 1970-01-01 PST.

How to get Current Epoch Timestamp in Ruby

Ruby provides the Time class to provide Date and Time-related functions.

There are multiple ways we can get current timestamp in Ruby One way, now method returns the Time object that holds current date and time. Second way using create a Time object and calls to_i method, Third way using time object, calls strftime object

Here is an example to get Current timestamp in Ruby

require 'time'

# Get Current timestamp with now
puts Time.now.to_i
# Get Current timestamp with new, to_i method
puts Time.new(2022, 1, 1).to_i
# Get Current timestamp with new method and strftime method
puts Time.new(2022, 1, 1).strftime("%s")

Output:

1654136928
1640995200
1640995200