更改纯红宝石的时区(不是铁轨)

Ell*_*ian 8 ruby time timezone sinatra

我正在建立一个混合了UTC/PST数据源的Sinatra站点,但将在PST中查看.所以我需要一种方法来轻松地将时间对象从UTC转换为PST.如果没有Rails的,我没有访问Time.zone,in_time_zone等等.

我只需要更改Time对象的时区,例如 2014-08-14 21:44:17 +0000 => 2014-08-14 14:44:17 -0700.

首先我尝试了这个:

class Time
  def to_pst
    self.utc + Time.zone_offset('PDT')
  end
end
Run Code Online (Sandbox Code Playgroud)

但这会改变实际的时间戳而不是区域.我需要两个time.to_i并且time.strftime工作; 所以我不能改变时间戳的绝对值.

> t = Time.now
=> 2014-08-14 21:46:20 +0000
> t.to_pst
=> 2014-08-14 14:46:20 UTC
> t.to_i
=> 1408052780
> t.to_pst.to_i
=> 1408027580
Run Code Online (Sandbox Code Playgroud)

gem'timezone'提出了类似的问题.

解决方案有效,但会改变全局变量,并且不是线程安全的.

操作系统时区需要保持UTC.

我只需要一种方法来改变单个Time对象的时区.这是一个简单的问题,它似乎应该有一个简单的解决方案!有没有人找到一个?提前致谢!

Siv*_*gam 9

在纯Ruby中

Time.now.utc.localtime("+05:30")
Run Code Online (Sandbox Code Playgroud)

其中+05:30(IST)是特定区域的偏移量


Pat*_*ity 8

您可以Time在Rails之外使用Active Support中的扩展:

require 'active_support/core_ext/time'

t = Time.now
#=> 2014-08-15 15:38:56 +0200

t.in_time_zone('Pacific Time (US & Canada)')
#=> Fri, 15 Aug 2014 06:38:56 PDT -07:00
Run Code Online (Sandbox Code Playgroud)

现在你可以做到

class Time
  def to_pst
    in_time_zone('Pacific Time (US & Canada)')
  end
end

t = Time.now
#=> 2014-08-15 15:42:39 +0200

t.to_i
#=> 1408110159

t.to_pst
#=> Fri, 15 Aug 2014 06:42:39 PDT -07:00

t.to_pst.to_i
#=> 1408110159

# timestamp does not change!
Run Code Online (Sandbox Code Playgroud)

此外,您可能还需要时间扩展NumericDate:

require 'active_support/core_ext/date'
require 'active_support/core_ext/numeric/time'

2.days.from_now
#=> 2014-08-17 15:42:39 +0200
Run Code Online (Sandbox Code Playgroud)