2015-05-27 78 views
2

我需要将日期字符串转换为Unix时间戳格式。 我从API中得到的字符串看起来像:Ruby - 将格式化日期转换为时间戳

2015-05-27T07:39:59Z 

.tr()我得到:

2015-05-27 07:39:59 

这是一个很普通的日期格式。尽管如此,Ruby无法将其转换为Unix TS格式。我试过.to_time.to_i,但我总是收到NoMethodError错误。

在PHP中,函数strtotime()正好适用于此。 Ruby有没有类似的方法?

+0

不这有帮助吗? http://ruby-doc.org/core-2.2.0/Time.html#method-i-strftime – lcguida

回答

7

您的日期字符串为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解析它

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

试试这个

1
require 'time' 

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

或者,使用Rails:

str.to_time.to_i 
2

在轨道4,您可以像使用 - string.to_datetime.to_i

"Thu, 26 May 2016 11:46:31 +0000".to_datetime.to_i 
相关问题