Set current Time.zone in Rails?

余生长醉 提交于 2019-12-17 23:08:06

问题


Javascript on my page saves client UTC offset to the cookie. How do I use this cookie to create a TimeZone and assign it to Time.zone ?

I need something like:

before_filter :set_time_zone

def set_time_zone
  Time.zone = ActiveSupport::TimeZone.new('my timezone', cookies[:timezone])
end

except that the right part of this expression does not work and I'm not sure if I'm going the right way here. Can't get it.


回答1:


Here's the working googled answer:

min = cookies[:timezone].to_i
Time.zone = ActiveSupport::TimeZone[-min.minutes]

Just to make it clear, the javascript part:

if(!($.cookie('timezone'))) {
  current_time = new Date();
  $.cookie('timezone', current_time.getTimezoneOffset(), { path: '/', expires: 10 } );
} 



回答2:


@snitko - you're answer worked great for me for a long time. However, as @Giovanni pointed out, it doesn't account for daylight savings time in some scenarios since it pulls the first timezone available given the minute offset. I've found a simple working answer that accounts for DST.

Head here - http://site.pageloom.com/automatic-timezone-detection-with-javascript, it's a javascript timezone detector. You simply copy the javascript code linked from the website (or right here) into your one of your app's javascript files (application.js works fine). It allows you to retrieve the timezone through an object named jstz.

Then, in application.html.erb I have

<script type="text/javascript">

  var timezone = jstz.determine();
  document.cookie = 'time_zone='+timezone.name()+';';

</script>

And in application_controller.rb, I have

before_filter :set_timezone 

private
def set_timezone
  Time.zone = cookies["time_zone"]
end

And that's all you need! Time zone is set properly for your Rails app.

EDIT: It's possible you need to place the javascript cookie setting code after your <\body> tag in application.html.erb due to the different way and order javascript files are loaded up.




回答3:


When I have it stored in my User model it is as simple as this

def set_time_zone
  Time.zone = current_user.time_zone unless current_user.blank?
end

so maybe you could do

def set_time_zone
  Time.zone = cookies[:timezone]
end

That's untested, I've never tried to do it from a cookie, I think it makes more sense to store it in the User model.



来源:https://stackoverflow.com/questions/942747/set-current-time-zone-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!