-
-
Save narath/c6331e18b0689e9623d73f8d033c247c to your computer and use it in GitHub Desktop.
Get timezone offset from the browser and use it for timezones in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jquery-cookies retired, moved this to js-cookie which no longer requires jQuery | |
import Cookies from 'js-cookie' | |
Cookies.set('tz', (new Date()).getTimezoneOffset()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
before_filter :set_timezone | |
# … | |
private | |
def set_timezone | |
# if the user has set their time_zone we default to that | |
# if there is no user.time_zone set, then we default to the browser time_zone | |
if current_user | |
if current_user.time_zone | |
Time.zone = current_user.time_zone | |
logger.info("Using current_user.time_zone #{current_user.time_zone}") | |
elsif browser_timezone | |
Time.zone = browser_timezone | |
logger.info("Using browser_timezone since current_user does not have time_zone set") | |
end | |
elsif browser_timezone | |
Time.zone = browser_timezone | |
logger.info("Not logged in, so using browser_timezone") | |
end | |
end | |
def browser_timezone | |
@browser_timezone ||= begin | |
ActiveSupport::TimeZone[-cookies[:tz].to_i.minutes] | |
end if cookies[:tz].present? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment