{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

How to remove an element from an array in Ruby Programming| Ruby on Rails by Example

How to check the type of a variable is Ruby| Ruby on Rails By Example

How to print the name of a Ruby class| Ruby on Rails By Example

How to check if the variable is defined in Ruby with examples

How to Find the minimum and maximum values in an array and hash Ruby with examples

How to Generate Random number in Ruby with examples

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