Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 838
Daniel Beardsley Avatar asked Dec 17 '10 04:12

Daniel Beardsley


People also ask

How do you change timezone in Ruby?

You can do: Time. now + Time. zone_offset("PST") if you: require 'time' in your ruby script. guess, should have done that before commenting.


1 Answers

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 
like image 55
Alex Kremer Avatar answered Oct 05 '22 12:10

Alex Kremer