How to save dates in local timezone to db with rails3?

做~自己de王妃 提交于 2020-01-10 10:42:30

问题


I have Rails3 application with model user and field expires_at created like this:

t.column :expires_at, :timestamp

In my database (postgresql) it has type:

timestamp without timezone

The problem is when I call:

@user.expires_at = Time.now
@user.save

it is saved into database with UTC timezone (my local time is UTC + 1:00, Warsaw) but I don't want that. I just want to have time with my local timezone saved into the database (2011-03-30 01:29:01.766709, not 2011-03-29 23:29:01.766709)

Can I achieve this using rails3?


回答1:


For saving time in local timezone to database this has to be set in application.rb

 config.active_record.default_timezone = :local



回答2:


If you only want to use local times on certain columns, rather than as a global setting, then the Rails documentation tells us this:

# If your attributes are time zone aware and you desire to skip time zone conversion to the current Time#zone when reading certain attributes then you can do following:

class Topic < ActiveRecord::Base
  self.skip_time_zone_conversion_for_attributes = [:written_on]
end

(This also skips time zone conversion on writing, not just reading). And you can pass in an array of symbols for multiple attributes.

I am not sure which versions of Rails this was introduced in, though.



来源:https://stackoverflow.com/questions/5480259/how-to-save-dates-in-local-timezone-to-db-with-rails3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!