Ruby - Convert formatted date to timestamp

ぐ巨炮叔叔 提交于 2020-01-02 07:52:08

问题


I need to convert a date string to the Unix timestamp format. The string I get from an API looks like:

2015-05-27T07:39:59Z

with .tr() i get:

2015-05-27 07:39:59

which is a pretty regular date format. Nonetheless, Ruby isn't able to convert it to Unix TS format. I tried .to_time.to_i but I keep getting NoMethodError Errors.

In PHP the function strtotime() just works perfectly for this. Is there some similar method for Ruby?


回答1:


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




回答2:


require 'time'

str = "2015-05-27T07:39:59Z"
Time.parse(str).to_i # => 1432712399

Or, using Rails:

str.to_time.to_i



回答3:


In rails 4, you can use like - string.to_datetime.to_i

"Thu, 26 May 2016 11:46:31 +0000".to_datetime.to_i



回答4:


string.tr!('TO',' ')
Time.parse(string)

Try this one



来源:https://stackoverflow.com/questions/30480779/ruby-convert-formatted-date-to-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!