Epoch and Date Time Conversion in Ruby

Ruby is a popular interpreted, high-level, general-purpose programming language. Ruby is a dynamically typed, uses garbage collection and supports multiple programming paradigms, including procedural, object-oriented, and functional programming. It has class DateTime to handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.

Here we will explain Ruby date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in Ruby

We will use the DateTime to get the current timestamp.

currentTimestamp = DateTime.now

Convert epoch or Unix timestamp to date in Ruby

We will use the DateTime.strptime to convert the epoch or timestamp to readable date format.

DateTime.strptime("1318996912",'%s')


Convert date to epoch or unix timestamp in Ruby

We can convert human readable date to timestamp using ToUnixTimeMilliseconds() method.

DateTime.new(2021, 2, 21).to_time.to_i


More about date time in Ruby