加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在ruby中解析任意gmt偏移的时间

发布时间:2020-12-17 02:34:01 所属栏目:百科 来源:网络整理
导读:我在Rails 3.2中运行,我无法想出一个很好的方法来解析在任意时区给我的时间. 作为一个例子,这是我在单独的键中给出的格式 { "start_date"="2013-04-24 13:00:00","timezone"="America/Los_Angeles","timezone_offset"="GMT-0700",...} This question非常接近
我在Rails 3.2中运行,我无法想出一个很好的方法来解析在任意时区给我的时间.

作为一个例子,这是我在单独的键中给出的格式

{
  "start_date"=>"2013-04-24 13:00:00","timezone"=>"America/Los_Angeles","timezone_offset"=>"GMT-0700",...
}

This question非常接近回答:

time = ActiveSupport::TimeZone.new('UTC').parse('2010-02-05 01:00:01')

问题是当我把“America / Los_Angeles”作为Timezone.new的论据时,它吐出了GMT-8的时区,我认为由于DST的变化.另一方面,我收到的数据定义了GMT的时区偏移量.因此,对于我的示例,期望的输出是GMT-7的时区.

如果我知道gmt偏移量而不是使用时区名称,有没有办法获得时区?

解决方法

您可以在ActiveSupport :: Timezone上使用[],以小时为单位传递gmt偏移量作为参数.

如api.rubyonrails.org所示:

[](ARG)

Locate a specific time zone object. If the argument is a
string,it is interpreted to mean the name of the timezone to locate.
If it is a numeric value it is either the hour offset,or the second
offset,of the timezone to find. (The first one with that offset will
be returned.) Returns nil if no such time zone is known to the system.

代码示例:

ActiveSupport::TimeZone["America/Los_Angeles"]                              
 => (GMT-08:00) America/Los_Angeles
ActiveSupport::TimeZone[-8]                              
 => (GMT-08:00) America/Los_Angeles

那么,你要做的是:

time = ActiveSupport::TimeZone[-7].parse('2013-04-24 13:00:00')

但是,请注意,因为偏移量可能相当于一个以上的时区,因为许多时区可能位于相同的偏移量上.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读