0

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

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

4

1 回答 1

0

不知道你从哪里得到你的区域字符串,但检查一下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

于 2013-01-21T22:01:40.460 回答