我生成了这样的模型:
class CreateMyModel < ActiveRecord::Migration
def change
create_table :my_model do |t|
t.references :place, index: true
t.time :time_first
t.time :time_second
t.timestamps
end
end
end
将模型保存到mysql中效果良好。时间列填充为hh:mm:ss,这很好。但当我从mysql中检索条目时,不知何故,它包含了2000-01-01的日期,例如:
2000-01-01T17:00:00Z
如何将时间列检索为hh:mm:ss?
我查询的表条目如下:
my_model = MyModel.find(id)
print my_model.to_json#here time_first and time_second include date.
将其用于mint中的时间和小时:
my_model.time_second.strftime("%H:%M %S %p")
ruby中没有只包含时间的数据类型,因此即使您将其作为只包含时间列保存到数据库中,它也将始终被解析为带时间的日期(默认为2000年1月1日)。不过,您可以定义一个属性读取器,将解析的日期时间转换为您喜欢的格式,例如"HH:MM:SS"字符串或今天的时间:
class MyModel < ActiveRecord::Base
# this will return the time formatted as a string:
def time_first
read_attribute(:time_first).strftime("%H:%M:%S")
end
# or
# this will return the time as todays datetime object:
def time_first
Time.parse(read_attribute(:time_first).strftime("%H:%M:%S"))
end
end
选择一种最适合您需求的方法。