How do I alter the timezone of a DateTime in Ruby?

2019-01-22 12:51发布

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.

I want this:

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

Is there any better way?

7条回答
ら.Afraid
2楼-- · 2019-01-22 13:44

As @Sam pointed out, changing offset is not sufficient and would lead to errors. In order to be resistant to DST clock advancements, the conversion should be done in a following way:

d = datetime_to_alter_time_zone
time_zone = 'Alaska'

DateTime.new
  .in_time_zone(time_zone)
  .change(year: d.year, month: d.month, day: d.day, hour: d.hour, min: d.min, sec: d.sec)
查看更多
登录 后发表回答