开发者

How to handle date/times in POST parameters?

By default, Rails' config.time_zone is UTC. So, fields like created_at, updated_at are saved in UTC.

Now, presume user's time zone is Pacific Standard Time (PST).

In order to show dates and times in the user's time zone, I have set Time.zone to PST.

Now, when a user enters a date (in user's local time zone, which is PST) in a form, that date is received in the controller according to the setting of Time.zone.

But, I want to save all times in the database in UTC.

So, how would I go 开发者_开发技巧about converting any date/time field in-place in the parameters hash to UTC? I'm wondering if there is a solution where Rails can do the conversion automatically?

I would like that any date/time received for any datetime field be converted to UTC, without having to write the conversion code in every controller.

UPDATE

I tested by setting Time.zone to Pacific Time (US & Canada) as well as to Eastern Time (US & Canada) and then saving a model. The created_at time in both cases was in UTC. So that confirms that setting Time.zone has no effect on what time is saved by Rails in the created_at field. That value is effected only by the config.time_zone (which if not defined in application.rb will default to UTC)

I'm so confused by this all!


In the database, all dates are always saved as UTC. The config.time_zone parameter is setting the default value for Time.zone, just for display. So you don't have to do anything to get the behavior you desire, just keep Time.zone set correctly for the user, and rails takes care of the rest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜