Rails:如何在使用Heroku时获取当前用户的时区 [英] Rails: How to get the current user's time zone when using Heroku

查看:114
本文介绍了Rails:如何在使用Heroku时获取当前用户的时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Heroku上的网站时区设置为太平洋标准时间(PST):

  heroku config:add TZ = America / Los_Angeles 

用户的时间现在总是在PST - 无论他们是否在PST时区。



获取用户实际时区的最佳方式是什么(即他们所在的时区)?

我猜这可以使用Rails(或Javascript?)解决,而不是Heroku。

解决方案

有两种方法可以做到这一点。


  • 的确,您可以使用JavaScript来获取当前时间/时区。有可能用户的电脑时间设置不正确,在这种情况下,您显示的时区将不正确。



    由于您使用的是Rails,推荐使用方式是将JavaScript已经捆绑为一个宝石,如 detect_timezone_rails 。这使得它易于安装(因为它全部自动捆绑在资产管道中。)


  • 您可以使用IP地址来推断其国家和时区。这种情况下的危险是用户可能使用代理服务器,而且IP地址通常具有城市级别的解析度,但它可能或多或少是准确的,这在极少数情况下会给出错误的时区。



    使用IP地址,您可以获得他们的近似城市和经度/纬度。许多宝石可以在 Ruby Toolbox ,例如 geocoder 。根据纬度/经度,您可以使用像 timezone




您也可以使用上述之一,并允许用户手动更改他们的时区在您的网站上(或者将此设置存储在数据库中(如果已注册),或者作为浏览器中的Cookie)。如果您的时区错误,这非常有用。


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 are now always in PST--whether or not they are in the PST time zone.

What's the best way to get the user's actual time zone (i.e. the time zone of where they are physically located)?

I'm guessing that this can be solved using Rails (or Javascript?), as opposed to Heroku.

解决方案

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.

这篇关于Rails:如何在使用Heroku时获取当前用户的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆