Ruby/Rails: Converting a Date to a Unix Timestamp

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".

Ruby - Convert formatted date to timestamp

Your date string is in RFC3339 format. You can parse it into a DateTime object, then convert it to Time and finally to a UNIX timestamp.

require 'date'

DateTime.rfc3339('2015-05-27T07:39:59Z')
#=> #<DateTime: 2015-05-27T07:39:59+00:00 ((2457170j,27599s,0n),+0s,2299161j)>

DateTime.rfc3339('2015-05-27T07:39:59Z').to_time
#=> 2015-05-27 09:39:59 +0200

DateTime.rfc3339('2015-05-27T07:39:59Z').to_time.to_i
#=> 1432712399

For a more general approach, you can use DateTime.parse instead of DateTime.rfc3339, but it is better to use the more specific method if you know the format, because it prevents errors due to ambiguities in the date string. If you have a custom format, you can use DateTime.strptime to parse it

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).

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')

How can I convert this time format into the unix timestamp in Ruby?

Your code works. You forgot require 'time'

require 'time'
t="2015-10-01 23:10:11"
Time.parse(t).to_i
# => 1443766211

By the way, please always post the error. Otherwise we have to guess what the problem is.

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