【问题标题】:Ruby - Convert formatted date to timestampRuby - 将格式化日期转换为时间戳
【发布时间】:2015-08-09 10:33:01
【问题描述】:
我需要将日期字符串转换为 Unix 时间戳格式。
我从 API 获得的字符串如下所示:
2015-05-27T07:39:59Z
.tr() 我明白了:
2015-05-27 07:39:59
这是一种非常常规的日期格式。尽管如此,Ruby 无法将其转换为 Unix TS 格式。我尝试了.to_time.to_i,但我不断收到NoMethodError 错误。
在 PHP 中,函数 strtotime() 非常适合这个。
Ruby 有没有类似的方法?
【问题讨论】:
标签:
ruby
date
time
timestamp
【解决方案1】:
string.tr!('TO',' ')
Time.parse(string)
试试这个
【解决方案2】:
您的日期字符串采用 RFC3339 格式。您可以将其解析为 DateTime 对象,然后将其转换为 Time,最后转换为 UNIX 时间戳。
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
对于更通用的方法,您可以使用DateTime.parse 而不是DateTime.rfc3339,但如果您知道格式,最好使用更具体的方法,因为它可以防止由于日期字符串中的歧义而导致的错误。如果有自定义格式,可以使用DateTime.strptime解析
【解决方案3】:
require 'time'
str = "2015-05-27T07:39:59Z"
Time.parse(str).to_i # => 1432712399
或者,使用 Rails:
str.to_time.to_i
【解决方案4】:
在 rails 4 中,您可以使用 like - string.to_datetime.to_i
"Thu, 26 May 2016 11:46:31 +0000".to_datetime.to_i