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

Ruby - Convert formatted date to timestamp

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

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

试试这个

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

require 'time'

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

或者,使用 Rails:

str.to_time.to_i

在rails4中,可以使用like - string.to_datetime.to_i

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