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

查看:39
本文介绍了如何在 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天全站免登陆