Rails / Activerecord Database Time Zone

I have a database that is written using a non-rails application and read using a rails application. The database has a date and time field, and the data stored in this field is stored in Eastern time. In my rails application, I understand that I can set the applicationโ€™s time zone in the environment.rb file by running config.time_zone = 'Eastern Time (US & Canada)' . However, the rails assume that the data stored in the database is stored in UTC and converted from config.time_zone to UTC when it retrieves information from and from the database.

Is there a way to tell rails the data in this particular field, or even all my datetime fields, is Eastern Time, not UTC?

+6
timezone ruby-on-rails activerecord
source share
3 answers

In Rails 3.0.5 in application.rb, this works:

 config.time_zone = 'Central Time (US & Canada)' config.active_record.default_timezone = :local 
+8
source share

config.active_record.default_timezone . Tells ActiveRecord to interpret the database time as specified in the specified time zone and use this time zone to work with the created_at and updated_at attributes.

+1
source share

My first suggestion is to fix another application. In another application, the UTC offset with the date should be stored. If you try to solve the problem, you are just going to create more. For example, what happens when daylight saving time is on, then will the offsets change?

This is said and has no other choice - I would do something in these lines for the created_at field:

 def created_at_in_eastern DateTime.parse(self.created_at.strftime("%D %T EST")) if self.created_at end 

or you can use EDT depending on how the data is saved, just read the disclaimer at the top - it's a hack!

0
source share

All Articles