如何在 Ruby 中将日期与时间以及 UTC (18/Sep/2012:09:57:41 -0500) 转换为时间戳?



我需要将 18/Sep/2012:09:57:41 -0500 转换为 ruby 中的时间戳。

require 'date' 
date = Date.parse("18/Sep/2012:09:57:41 -0500")
date.to_time.to_i # => 1568782800

使用类方法DateTime::strptime,然后将生成的DateTime对象转换为使用DateTime#to_time的Time对象是最安全的。

DateTime#strptime使用的格式字符串的组成部分在 DateTime#strftime 的文档中给出。

str = "18/Sep/2012:09:57:41 -0500"

require 'time'
fmt = "%d/%b/%Y:%H:%M:%S %z"
DateTime.strptime(str, fmt).to_time
#=> 2012-09-18 09:57:41 -0500

Date.parse "Date::parse may work in unexpected ways so I tend to avoid using it."
#=> #<Date: 2019-05-01 ((2458605j,0s,0n),+0s,2299161j)> 

最新更新