How to Convert a Unix Timestamp (Seconds Since Epoch) to Ruby Datetime

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

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

Ruby: convert unix timestamp to date

Use Time.at.

Time.at(1335437221)
# => 2012-04-26 12:47:01 +0200

Ruby DateTime and epoch conversion

Convert to Time with .to_time and then to Unix Time with to_i. For example:

created_at = ModelName.where("created_at >= ? ", Time.zone.now).pluck(:created_at)
created_at.to_time.to_i

Conversion from epoch to datetime is incorrect

You are passing miliseconds to the Time::at() method. You should pass seconds there. Link to docs is here.

To retrieve Epoch value(in seconds), use Time#to_i

UPD

This will work for you:

Time.at(0, your_epoch_milliseconds, :millisecond)

Convert unix hex timestamp to ruby datetime

First you need to convert hex value to decimal.

Then, use Time.at() or DateTime.strptime() function to get the timestamp

2.5.3 :019 > DateTime.strptime(str.to_i(16).to_s, '%s')
=> Fri, 03 Sep 2021 12:08:29 +0000

2.5.3 :020 > Time.at(str.to_i(16))
=> 2021-09-03 17:38:29 +0530

Crossverified using https://www.epochconverter.com/hex

hex timestamp : 6132103D

Equivalent timestamp:

GMT: Friday, September 3, 2021 12:08:29 PM
Your time zone: Friday, September 3, 2021 5:38:29 PM GMT+05:30
Decimal timestamp/epoch: 1630670909

Ruby/Rails: converting a Date to a UNIX timestamp

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

Note that the intermediate DateTime object is in local time, so the timestamp might be several hours off from what you expect. If you want to work in UTC time, you can use DateTime's method "utc".

Convert from format date string to unix (epoch) time value

To convert the string into an array of integers, look into split('/'), to turn that into a unix time stamp look here (you probably want to_i but be warned that it incorporates your local time zone).

Converting Ruby timestamp to seconds in Epoch and back

Supposing your timestamp is a Ruby Time object:

puts time_stamp.strftime('%s')
puts time_stamp.to_i
timestamp = Time.at(628232400)

In case it is a DateTime object, you have the strftime and strptime methods at your disposal.

how to convert this (month/day/year ) date format to actual timestamp in rails

I think you just need format that string to valid format to convert to date, something like this:

old_format = '6/21/2021'.split('/')
old_format[0], old_format[1] = old_format[1], old_format[0]
old_format.join('/').to_date


Related Topics



Leave a reply



Submit