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

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

问题描述

我使用以下方法将我们网站在 Heroku 上的时区设置为太平洋标准时间 (PST):

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

heroku config:add TZ=America/Los_Angeles

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

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)?

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

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

推荐答案

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

There are two ways to do this.

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

  • 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.

因为您使用的是 Rails,所以推荐的方法是将 javascript 捆绑为 gem,例如 detect_timezone_rails.这使其易于安装(因为它全部自动捆绑在资产管道中.

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.

您可以使用 IP 地址来推断他们的国家和时区.这种情况下的危险在于用户可能正在使用代理.此外,虽然 IP 地址通常具有城市级别的分辨率,但它可能或多或少准确,在极少数情况下可能会给出错误的时区.

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.

使用 IP 地址,您可以获得他们的大致城市和纬度/经度.在 Ruby Toolbox 上有很多 gems 可以做到这一点,例如.geocoder.使用纬度/经度,您可以使用像 timezone.

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.

您也可以使用上述方法之一,并允许用户在您的网站上手动更改时区(如果已注册,则将此设置存储在数据库中,或作为浏览器上的 cookie).这在您弄错时区时很有用.

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天全站免登陆