Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timezone with rails 3

I have pretty common issue but for some reason i have tried all the suggestions on the web and none seem to work.

I have set the Timezone in config to 'EST'

config.time_zone = 'Eastern Time (US & Canada)'

But when the time is shown on the the screen, it continues to show the UTC time that is stored in the DB. I tried the debugger and here is the output

(rdb:1) Time.zone 
#<ActiveSupport::TimeZone:0x1061f4760 @utc_offset=nil, @current_period=nil, @name="Eastern Time (US & Canada)", @tzinfo=#<TZInfo::TimezoneProxy: America/New_York>>
(rdb:1) Order.first.placed_at
Fri Jan 01 15:00:00 UTC 2010

Update: Here is another user who has the same question Rails timezone is wrong when shown

like image 474
Addy Avatar asked Dec 06 '10 02:12

Addy


3 Answers

Try in_time_zone. For example

>> Time.now
=> Sun Dec 05 21:34:45 -0500 2010
>> Time.zone
=> #<ActiveSupport::TimeZone:0x1033d97b8 @name="Pacific Time (US & Canada)", @tzinfo=#<TZInfo::DataTimezone: America/Los_Angeles>, @utc_offset=-28800, @current_period=nil>
>> Time.now.in_time_zone
=> Sun, 05 Dec 2010 18:34:54 PST -08:00

In your case, you want Order.first.placed_at.in_time_zone.

like image 180
Paul Schreiber Avatar answered Nov 13 '22 14:11

Paul Schreiber


If you want to set a different time zone for different users of your app, make sure you use an around_filter as opposed to a before filter to change Time.zone. Something to do with how Time.zone leaks over to other threads and thus other users may inheret a time zone that they shouldn't. From this blog post: http://ilikestuffblog.com/2011/02/03/how-to-set-a-time-zone-for-each-request-in-rails/

in application_controller.rb:

around_filter :set_time_zone

private

def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.time_zone if logged_in?
  yield
ensure
  Time.zone = old_time_zone
end

I also found it helpful to use the time_zone_select form helper method when allowing users to change their time zone. If you called your field :time_zone, you would use it like:

f.time_zone_select(:time_zone)

And lastly, this looks pretty awesome. Auto detect and set time zone via javascript. Here's the rails gem to add to the asset pipeline: https://github.com/scottwater/detect_timezone_rails and accompanying blog post: http://www.scottw.com/automated-timezone-detection

like image 42
Danny Avatar answered Nov 13 '22 15:11

Danny


Check that your ActiveRecord::Base.time_zone_aware_attributes is true.

like image 2
Duke Avatar answered Nov 13 '22 15:11

Duke