Skip to content

Instantly share code, notes, and snippets.

@narath
Forked from bkeepers/application.js
Last active February 16, 2021 20:41
Show Gist options
  • Save narath/c6331e18b0689e9623d73f8d033c247c to your computer and use it in GitHub Desktop.
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
// jquery-cookies retired, moved this to js-cookie which no longer requires jQuery
import Cookies from 'js-cookie'
Cookies.set('tz', (new Date()).getTimezoneOffset());
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