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

前端 未结 3 1716
情话喂你
情话喂你 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 05:54

    There are two ways to do this.

    • Indeed, you can use javascript to fetch their current time/timezone. There is the possibility that the user's computer time is not set correctly, in which case the time zone you display will not be correct.

      Because you are using Rails, a recommended way is to get javascript already bundled as a gem, like detect_timezone_rails. This makes it easy to install (because it is all bundled automatically in the asset pipeline.

    • You can use the IP address to infer their country and time zone. The danger in this case is that a user may be using a proxy. Also, while the IP address generally has city-level resolution, it may be more or less accurate, which may in rare cases give the wrong time zone.

      Using the IP address, you can get their approximate city and latitude/longitude. There are many gems that can do this on Ruby Toolbox, eg. geocoder. With the latitude/longitude, you can get the time zone using a gem like timezone.

    You can also use one of the above, and allow the user to manually change their time zone on your website (either storing this setting in a database if registered, or as a cookie on their browser). This is useful in case you got the timezone wrong.

提交回复
热议问题