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

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


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

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


d = DateTime.nowputs [ d, d.zone ]#=> 2010-12-17T13:28:29-07:00#=> -07:00d2 = d.new_offset(3.0/24)puts d2, d2.zone#=> 2010-12-17T23:28:29+03:00#=> +03:00

Edit: This answer doesn't account for the information provided by comment to another answer that the desire is to have the reported 'hours' be the same after the time zone change.


Using a number offset e.g. '+1000' wont work all year round because of daylight savings. Checkout ActiveSupport::TimeZone. More info here