Rails 3 解析时区字符串,格式为:"(GMT-05:00) Eastern Time (US & Canada)"



如何将此时区字符串解析为正确的格式,以便我可以使用 Time.zone = <the proper time zone string>" .目前已知的格式类型是:Eastern Time (US & Canada),不知道为什么它不想接受更精确的格式,比如"(GMT-05:00)东部时间(美国和加拿大)"。

Rails 中是否有任何内置工具来处理我拥有的字符串,并将其修改为正确的 Time.zone 格式?请注意,该解决方案应正确映射到所有 Rail 的时区列表......

不确定从哪里获取区域字符串,但请检查此TimeZone.to_s

# Returns a textual representation of this time zone.
def to_s
  "(GMT#{formatted_offset}) #{name}"
end
# Returns the offset of this time zone as a formatted string, of the
# format "+HH:MM".
def formatted_offset(colon=true, alternate_utc_string = nil)
  utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon)
end

您所需要的只是Time.zone.name # => "Eastern Time (US & Canada)"

如果你没有,那么用正则表达式解析字符串

'(GMT-05:00) Eastern Time (US & Canada)'.match(/(.*) (.*)/)[1]
#=> "Eastern Time (US & Canada)"

https://github.com/rails/rails/blob/5fe88b11f11bb3b30bc23c57b36be4f027d915ba/activesupport/lib/active_support/values/time_zone.rb#L337

相关内容

最新更新