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

问题描述:

我需要将日期字符串转换为Unix时间戳格式。
从API获取的字符串如下所示:

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

.tr()我得到:

2015-05-27 07:39:59

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

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.

在PHP中,函数 strtotime()完全适用于此。
Ruby有一些类似的方法?

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

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

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

对于一般的方法,您可以使用 DateTime.parse 而不是 DateTime.rfc3339 ,但是如果您知道格式,最好使用更具体的方法,因为它可以防止日期字符串中的歧义导致的错误。如果您有自定义格式,可以使用 DateTime.strptime 来解析它

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