如何在Ruby中改变DateTime的时区? [英] How do I alter the timezone of a DateTime in Ruby?

查看:149
本文介绍了如何在Ruby中改变DateTime的时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读,写作和序列化日期和时间,同时保持时区不变,变得恼人。我使用Ruby(和Rails 3.0),并尝试更改DateTime的时区。 (到UTC),但不是时间本身。

Reading, writing, and serializing dates and times while keeping the time zone constant is becoming annoying. I'm using Ruby (and Rails 3.0) and am trying to alter the time zone of a DateTime. (to UTC) but not the time itself.

我想要这样:

t = DateTime.now
t.hour
-> 4
t.offset = 0
t.hour
-> 4
t.utc?
-> true

最近我来的是这个,但不直观。

The closest I have come is this, but it's not intuitive.

t = DateTime.now
t.hour
-> 4
t += t.offset
t = t.utc
t.hour
-> 4
t.utc?
-> true

有没有更好的方法?

推荐答案

使用Rails 3,您正在寻找DateTime.change()

Using Rails 3, you're looking for DateTime.change()

dt = DateTime.now
=> Mon, 20 Dec 2010 18:59:43 +0100
dt = dt.change(:offset => "+0000")
=> Mon, 20 Dec 2010 18:59:43 +0000

这篇关于如何在Ruby中改变DateTime的时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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