How to Convert current Unix timestamp epoch to DateTime in Ruby Programming| Ruby on Rails by Example

This tutorials explains about how to convert currrent unix timestamp to Datetime in Ruby.

You can check other about how to get current Epoch Timestamp

There are multiple ways we can convert epoch timestamp to Date time.

How to convert Unix Timestamp to Datetime in Ruby With example?

Time library provides methods to get current timestmap.

Time.now.to_i returns the current timestamp number. It is elapsed seconds since unix timestamp.

require 'time'

# Get Current timestamp with now
timestamp=Time.now.to_i
puts timestamp

Output:

1654736871

There are two ways we can convert to Datetime.

  • Time.at() method that returns Date time in Local timezone.
  • DateTime.strptime method that returns Date time in UTC timezone.

use Time.at method Time class provides at method which takes argument of number and returns Date time in Local Format.

Here is an example code

require 'time'
require 'date'

# Get Current timestamp with now
timestamp=Time.now.to_i
puts timestamp
puts Time.at(timestamp)

Output:

1654736871
2022-06-09 01:07:51 +0000
2022-06-09T01:07:51+00:00

Another way using DateTime.strptime.

strptime method takes string parameter and formatted date and time in UTC Timezone

Here is an examples

require 'time'
require 'date'

# Get Current timestamp with now
timestamp=Time.now.to_i
puts timestamp

puts DateTime.strptime(timestamp.to_s,'%s')

Output:

1654736871
2022-06-09T01:07:51+00:00

Convert Unix Timestamp to Date in Ruby

First convert to UTC date and time using Datetime.strptime() method

Convert this to Date using strftime() method with %d-%m-%y string format

Here is an example code

require 'time'
require 'date'

# Get Current timestamp with now
timestamp=Time.now.to_i
puts timestamp

puts DateTime.strptime(timestamp.to_s,'%s').strftime("%d-%m-%y")

Output:

09-06-22