1

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!

Community
  • 1
  • 1
Zabba
  • 64,285
  • 47
  • 179
  • 207

1 Answers1

1

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.

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
  • According to what I have tested, that does not seem true. Please see my question for update. – Zabba Feb 22 '11 at 03:50
  • I don't think I follow, your update reiterates what I said: config.time_zone does not affect how the date is stored in the database, it is always stored as UTC. What it _does_ affect, is the default timezone used when retrieving a date through one of the models accessor methods. For example Model.created_at will be returned in the timezone specified by config.time_zone, unless you have set Time.zone to override it. – Chris Cherry Feb 22 '11 at 04:08
  • If you would like to convert from one timezone to another manually you can use the method: in_time_zone, like so: model.created_at.in_time_zone('Eastern Time (US & Canada)') – Chris Cherry Feb 22 '11 at 04:09
  • Yes, you're right. I'm very confused about all the time-related stuff I've been doing :( I hate time zones! – Zabba Feb 22 '11 at 04:17
  • Maybe you could also look at my (one more!) question on time zones?: http://stackoverflow.com/questions/5073917/why-doesnt-config-time-zone-seem-to-do-anything – Zabba Feb 22 '11 at 04:18