Search code examples
ruby-on-railstimezoneactivesupport

Can't set timezone using abbreviation


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


Solution

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