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?
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: