Rails 将 UNIX 时间戳转换为 SQL 日期时间

Rails Convert UNIX timestamp to SQL DateTime

我的时间戳为“1432927800000”

我想将它保存在 MySQL 的 DateTime 列中。 (SQL DateTime 列以这种格式存储日期:2010-06-24 11:30:00

我试过了

uTime = params[:fromDate] #contains "1432927800000"
Date.new(uTime).to_formatted_s(:db) #Comparison of String with 0 failed.
DateTime.strptime("1318996912",'%s') #Give weird date: Wed, 03 Sep 47377 12:00:00 +0000
Date.parse(uTime).to_s(:db) #Invalid Date

我期待 2015-5-30 1:00:00 来自“1432927800000”

试试这个希望对你有帮助

我已经在我的 Rails 控制台 中尝试过了,我得到了关注。

uTime = 1432927800000

Time.at(uTime/1000).strftime("%Y-%m-%d %I:%M:%S")

## Output

"2015-05-30 01:00:00"

这是一个link你会帮助你转换unix时间戳的地方 http://www.epochconverter.com/

而不是 strftime 将更好地使用来自 ActiveSupport 的预定义 :db pattern

2.1.0 :002 > Time.at(1432927800000/1000).to_s(:db)
 => "2015-05-29 22:30:00"

to_sto_formatted_s 方法的别名,在 TimeDateTime 类.

中定义