Can't set timezone using abbreviation

喜欢而已 提交于 2019-12-02 07:43:43

jstimezone was reporting timezone using abbreviations. It is also quite buggy and unmaintained (https://bitbucket.org/pellepim/jstimezonedetect/issues?status=new&status=open). It is simpler to just use standard javascript:

var offset = - new Date().getTimezoneOffset()/60

Then call on document ready:

$.cookie("browser.tzoffset", offset, { expires: 30, path: '/' })

Then in rails use around_filter in ApplicationController:

  def set_time_zone
    return yield unless (utc_offset = cookies['browser.tzoffset']).present?
    utc_offset = utc_offset.to_i
    gmt_offset = if utc_offset == 0 then nil elsif utc_offset > 0 then -utc_offset else "+#{-utc_offset}" end
    Time.use_zone("Etc/GMT#{gmt_offset}"){ yield }
  rescue ArgumentError
    yield
  end

This localizes all dates for users, independently where he/she is. In Brazil we have multiple timezones, for example.

PS: ActiveSupport::TimeZone[utc_offset.to_i] can't be used as it uses DST, see https://github.com/rails/rails/issues/20504

PS: You can also use moment: moment.parseZone(Date.now()).utcOffset()/60 or moment().format('zz')

You don't have to use around_filter. Put this in before_action

Time.zone = "Etc/GMT#{gmt_offset}"

(Time.zone is thread local. It's safe to change.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!