使用Rails 3和PostgreSQL 8,我有一个fuel_date列,数据类型为“timestamp without time zone”。用户在本地时间从下拉菜单中选择日期和时间,当它提交给服务器时,应将其保存为UTC时间:
def create_fuel_service
attributes = {}
fuel_service_hash = params[:fuel_service]
datetime = DateTime.new(fuel_service_hash["fuel_date(1i)"].to_i, fuel_service_hash["fuel_date(2i)"].to_i,
fuel_service_hash["fuel_date(3i)"].to_i, fuel_service_hash["fuel_date(4i)"].to_i,
fuel_service_hash["fuel_date(5i)"].to_i).in_time_zone(current_user.time_zone).utc
attributes[:fuel_date] = datetime
fuel_service = FuelService.new(attributes)
if fuel_service.save
...
但是,即使created_at和updated_at字段保存为UTC时间,记录也会保存为本地时间而非UTC时间:
http://s22.postimg.org/caho7v6c1/utctime_issue.png
如何在保存前将fuel_date字段转换为UTC时间?使用DateTime的UTC时间方法不起作用。
答案 0 :(得分:0)
最终工作的是使用Time.new而不是DateTime.new:
datetime = Time.new(fuel_service_hash["fuel_date(1i)"].to_i, fuel_service_hash["fuel_date(2i)"].to_i,
fuel_service_hash["fuel_date(3i)"].to_i, fuel_service_hash["fuel_date(4i)"].to_i,
fuel_service_hash["fuel_date(5i)"].to_i)