Rails: How to get the current user's time zone when using Heroku

前端 未结 3 1717
情话喂你
情话喂你 2020-12-08 05:44

I set the time zone of our site on Heroku to Pacific Standard Time (PST) using:

heroku config:add TZ=America/Los_Angeles

Times for users ar

3条回答
  •  我在风中等你
    2020-12-08 06:01

    There is a couple of ways you could do this depending on how you app is set up. None of which are unique to the Heroku environment.

    If your app allows users to sign up then you most probably have a User model, and you may be using the Devise gem for authentication/signup. Add a field to your db (:time_zone) and store the users time zone in this field when they sign up.

    >> rails generate migration add_time_zone_to_users time_zone:string
    >> rake db:migrate
    

    Rails gives you a handy time_zone_select form helper which gives you a select list with all the Time zones in it which you can display to your user. Add it to the user sign up form and allow the user to set their time zone when signing up. http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/time_zone_select

    In your Application Controller you can then do something like this;

    before_filter :set_time_zone
    
    def set_time_zone
        #current user is a devise method see https://github.com/plataformatec/devise
        Time.zone = current_user.time_zone if current_user
    end
    

    Then when you display a date in your app call .in_time_zone on the time instance which will display the time in the users time zone.

    <%= Time.now.in_time_zone %> or <%= @your_model.created_at.in_time_zone %> 
    

    If you don't have user authentication then you could fall back to javascript. To do this you could use the native javascript getTimezoneOffset() on the date object, or even better use the following jsTimezoneDetect plugin:

    http://www.pageloom.com/automatic-timezone-detection-with-javascript

    Finally you could use a hybrid of both and firstly detect their time zone offset using javascript and then store this value in a rails session/cookie and then use a before_filter to set the Time.zone as above but based on the session time_zone value previously calculated in javascript.

提交回复
热议问题