gpt4 book ai didi

ruby - 有没有办法获取本地时区的 TZInfo 样式字符串?

转载 作者:数据小太阳 更新时间:2023-10-29 07:39:33 26 4
gpt4 key购买 nike

我需要尝试获得一个 TZInfo 样式字符串 a-la 'America/New_York' 代表我所在系统的本地时区。我不知道该怎么做。

Time.zone

#<ActiveSupport::TimeZone:0x007ff2e4f89240 @name="UTC", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Etc/UTC>, @current_period=#<TZInfo::TimezonePeriod: nil,nil,#<TZInfo::TimezoneOffsetInfo: 0,0,UTC>>>>

这里的 TimezoneProxy#Etc/UTC 字段是我想要的样式,但 UTC 不是本地时间。

Time.now.zone

"EST"

这里的“EST”不是我想要的,我看不到将 Time.now 或 EST 传递给 TZInfo 以获得我想要的东西的方法?

有没有办法根据我当前的时区获取“America/New_York”甚至所有等效时区字符串的列表?

最佳答案

您可以尝试通过以下方式查找所有 EST 别名:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
all.
select{|tz| tz.utc_offset == current_tz.utc_offset }.
map(&:tzinfo).
map(&:name).
uniq

会产生

["America/Bogota", "EST", "America/New_York", "America/Indiana/Indianapolis", "America/Lima"]

但我认为这是不正确的,因为夏令时问题。更正确的代码:

current_tz = ActiveSupport::TimeZone['EST']
ActiveSupport::TimeZone.
all.
select{|tz|
tz.utc_offset == current_tz.utc_offset &&
tz.tzinfo.current_period.dst? == current_tz.tzinfo.current_period.dst?
}.
map(&:tzinfo).
map(&:name).
uniq

会产生

["America/Bogota", "EST", "America/Lima"] 

关于ruby - 有没有办法获取本地时区的 TZInfo 样式字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com