Ruby – 将格式化日期转换为时间戳

我需要将日期字符串转换为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有一些类似的方法吗?

您的日期字符串是RFC3339格式。 您可以将其解析为DateTime对象,然后将其转换为Time ,最后转换为UNIX时间戳。

 require 'date' DateTime.rfc3339('2015-05-27T07:39:59Z') #=> # 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来解析它

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

或者,使用Rails:

 str.to_time.to_i 

在rails 4中,您可以使用like – string.to_datetime.to_i

 "Thu, 26 May 2016 11:46:31 +0000".to_datetime.to_i 
 string.tr!('TO',' ') Time.parse(string) 

试试这个