Can't set timezone using abbreviation

和自甴很熟 提交于 2019-12-04 05:58:40

问题


I can't set timezone on Rails using its abbreviation, for example:

>> Time.zone = 'BRT'
ArgumentError: Invalid Timezone: BRT
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:61:in `rescue in find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:53:in `find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:37:in `zone='
        from (irb):14
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

This is necessary as some systems (android and some browsers) report timezone using the abbreviation. The list of abbreviations can be found at http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/30756405/cant-set-timezone-using-abbreviation

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