Tuesday, February 10, 2009

Rails / ActiveRecord : Created_At and GMT (or is it UTC?)

I’ve got a production Rails app (yay!) running side by side with a legacy PHP app, and the model is mixed – my new User object has_many of the old php Account object.    This is fine, they’ve agreed to behave, but there’s a problem.  The created_at and other timestamp info on my Users table is in GMT(*), while the Accounts table is in local.  I need these to be consistent because there’s logic I have to write relative to the creation times (i.e. how long after the user was created, was the account created…).  Is there a configuration available to me in Rails that will force created_at to be local time instead of GMT(*)?

(*) It is actually my own local time (EST) +5.  I keep calling it GMT, but not sure that’s accurate.

UPDATE:  Ok, if I understand this right, it’s using UTC because I don’t have a default timezone set.  I can live with that.  But why, in irb or script/console, if I do “Time.now.zone” does it say EST?  Doesn’t that mean that either a) I do have it set someplace, or else b) Rails is smart enough to figure it out?  Where then is the “no default, therefore UTC” thing being invoked, that I have to change?

UPDATE:  Never mind, I’m an idiot, it’s right there in config/environment.rb:

# Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
# Run “rake –D time” for a list of tasks for finding time zone names. Comment line to use default local time.
# config.time_zone = ‘UTC’


Scott Wolff said...

Thanks for this,it helped me out today. Funny how the documentation often has the answer.

Anonymous said...

Thanks, it worked for me also!