Can't set timezone using abbreviation

前端 未结 2 875
天命终不由人
天命终不由人 2021-01-27 14:17

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

>> Time.zone = \'BRT\'
ArgumentError: Invalid Timezone: BRT
        from /home/braulio/         


        
相关标签:
2条回答
  • 2021-01-27 14:54

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

    0 讨论(0)
  • 2021-01-27 14:55

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

    0 讨论(0)
提交回复
热议问题