rom*_*ipp 3 ruby time timestamp date
我需要将日期字符串转换为Unix时间戳格式.我从API获得的字符串如下所示:
2015-05-27T07:39:59Z
Run Code Online (Sandbox Code Playgroud)
与.tr()
我得到:
2015-05-27 07:39:59
Run Code Online (Sandbox Code Playgroud)
这是一种非常规则的日期格式.尽管如此,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: 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
Run Code Online (Sandbox Code Playgroud)
对于更通用的方法,您可以使用DateTime.parse
而不是DateTime.rfc3339
,但如果您知道格式,则最好使用更具体的方法,因为它可以防止由于日期字符串中的歧义而导致的错误.如果您有自定义格式,则可以使用DateTime.strptime
它来解析它