Rails time zone selector: intelligently selecting a default
When signing up for an account on one of my apps, we need to store the time zone is in. We're开发者_如何学编程 using the time zone selector, which is fine, but I'd like to set the default value to something that it likely the user's current time zone.
Is there an easy way, either on the server or using JavaScript, to set the time zone selector to the time zone the user is currently in?
On page load, get the browser's offset from GMT, and use this to pre-select the time zone selector.
var offestFromGMT = - new Date().getTimezoneOffset() / 60
You can check the UTC offset using data such as those from IP2Location which are based on the IP address of the user. With that you should be able to easily accomplish what you were looking for.
Geocoding might be better than nothing, but you have to be careful, because often the geocoding will tell you where the ISP is, but not where the actual user is. getTimezoneOffset() is more effective since it uses the browser TZ, not the ISP TZ.
From my understanding, there is no HTTP header for a users timezone or a users current time.
The best way to deal with this use case, in my opinion, is to use ip address geocoding on the server side and then translate this to a timezone using a service like ip2address.
This does mean if the geocoding and timezone resolution is slow serving the request will be slow too.
I would also allow for customization as well because the service can not be 100% relied upon (users might be vpning to your site through their company firewall). Also, I would only do this resolution once and then store the results in a cookie.
精彩评论