How Would I Go About Converting This Time String to Epoch Time in Ruby

How would I go about converting this time string to epoch time in ruby?

For example:

require 'date'

# as an integer:
DateTime.parse('2012-12-13T14:43:35.371Z').to_time.to_i
# or as a string:
DateTime.parse('2012-12-13T14:43:35.371Z').strftime('%s')

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

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

Convert epoch time in Ruby (Long string)

Use DateTime#strptime with "%Q" formatter for parsing milliseconds.

require 'date'
DateTime.strptime 1520486517000.to_s, '%Q'
#⇒ #<DateTime: 2018-03-08T05:21:57+00:00 ((2458186j,19317s,0n),+0s,2299161j)>

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 - epoch time with milliseconds to local time string

Try Time.at(1475001600079 / 1000.0).

The epoch time in ruby is in seconds, not milliseconds.

As to the NoMethodError, you need to require 'time' before you call Time::strptime.

Finally the format you need:

Time.at(1475001600079 / 1000.0).strftime('%Y/%m/%d %H:%M:%S.%3N')

Convert epoch time in Ruby

Use the Time.at method:

Time.at(1234567890) #=> 2009-02-13 16:31:30 -0700

To display the time, you can use the method strftime on the resulting object.

For instance:

Time.at(1234567890).strftime("%m/%d/%Y") #=> "02/13/2009"

Ruby: How to convert a date-time string to a floating point number in epoch time?

Use Time::parse, a Ruby stdlib library function, then call to_f on the resulting Time object.

require 'time'
str = 'Feb 1, 2014 06:47:42.93'
Time.parse(str).to_f

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.



Related Topics



Leave a reply



Submit