I set the local timezone in Rails with this javascript function in my layout:
<script type="text/javascript" charset="utf-8">
<% unless session[:timezone_offset] %>
$.ajax({
url: '/main/timezone',
type: 'GET',
data: { offset: (new Date()).getTimezoneOffset() }
});
<% end %>
</script>
where this is the receiving function:
# GET /main/timezone AJAX
#----------------------------------------------------------------------------
def timezone
#
# (new Date()).getTimezoneOffset() in JavaScript returns (UTC - localtime) in
# minutes, while ActiveSupport::TimeZone expects (localtime - UTC) in seconds.
#
if params[:offset]
session[:timezone_offset] = params[:offset].to_i * -60
ActiveSupport::TimeZone[session[:timezone_offset]]
end
render :nothing => true
end
And then I have the offset in my session, so I do something like this to show a time:
<%= (@product.created_at + session[:timezone_offset]).strftime("%m/%d/%Y %I:%M%p") + " #{ActiveSupport::TimeZone[session[:timezone_offset]]}" %>
Is all of this really necessary in Rails 3? I think the first two code blocks may be, but the third seems a bit excessive...