更改纯 ruby​​ 中的时区(不是 rails) [英] Change Time zone in pure ruby (not rails)

查看:53
本文介绍了更改纯 ruby​​ 中的时区(不是 rails)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a Sinatra site which has mixed UTC/PST data sources, but will be viewed in PST. So I need a way to easily convert Time objects from UTC to PST. Without Rails, I don't have access to Time.zone, in_time_zone, etc.

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

I only need to change the timezone of a Time object, E.g. 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

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

But this changes the actual timestamps and not the zone. I need both time.to_i and time.strftime to work; so I can't change the absolute value of the timestamps.

> 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

gem 'timezone' 也存在类似的问题.

这个 解决方案有效但改变了全局变量,而不是线程-安全.

This solution works but alters global variables and is not thread-safe.

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

The OS time zone needs to stay UTC.

我只需要一种方法来更改单个 Time 对象上的时区.这是一个简单的问题,看起来应该有一个简单的解决方案!有人找到了吗?提前致谢!

I simply need a way to change the Time zone on a single Time object. This is a simple problem and it seems like it should have a simple solution! Has anyone found one? Thanks in advance!

推荐答案

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

You can use the Time extensions from Active Support outside of Rails:

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

现在可以了

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!

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

Additionally you might also want the time extensions on Numeric and Date:

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

2.days.from_now
#=> 2014-08-17 15:42:39 +0200

这篇关于更改纯 ruby​​ 中的时区(不是 rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆