将字符串中的主动支持时区对象转换回导轨中的对象



如何将主动支持时间对象转换为字符串回对象,换句话说,如何从其字符串中找到活动支持对象?

示例:

 a = ActiveSupport::TimeZone.all.first = 
#<ActiveSupport::TimeZone:0x007f8c45bc1848 @name="American Samoa", 
@tzinfo=#<TZInfo::TimezoneProxy: Pacific/Pago_Pago>, @utc_offset=nil>

如果我使用to_s将此对象转换为字符串,我会得到"(GMT-11:00)American Samoa。

如果我有"(GMT-11:00)American Samoa"。

这将消除第一对括号之间的所有内容,并抓住其余的字符串:

a = ActiveSupport::TimeZone.all.first.to_s.match(/(.*?) (.*)/)[1]

...您可以找到ActiveSupport::Timezone对象:

ActiveSupport::Timezone[a]

# let
timezone_string = '(GMT-11:00) American Samoa'
# let's capture the "American Samoa" substring from above (as an example)
matches = timezone_string.match /(GMT.*?) (.*)/
timezone_name = matches[1]
# then we look up the corresponding Timezone object using the "American Samoa" timezone_name
timezone = ActiveSupport::TimeZone[timezone_name]

谢谢您的答案,我尝试了它们并有效。我也尝试了这个

tz_value = business_timezone.split(')').second.strip 

给我这个名字,我正在使用

找到对象
ActiveSupport::TimeZone[tz_value].

最新更新