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?
You can specify the Time Zone you want to use in your app by adding the following line in the config file (config/application.rb): config.time_zone = 'Mumbai'
You can find the official documentation for the same here: http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html
The other option is that you "Monkey Patch" the 'DateTime' class.
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 Rails 3, you're looking for DateTime.change()
If someone(like me) has time zone in string format like "Pacific Time (US & Canada)"
Than this is the best way i found:
Using a number offset e.g. '+1000' wont work all year round because of daylight savings. Checkout ActiveSupport::TimeZone. More info here
I would use a Time object instead. So get the current local time then increment it by the UTC offset and convert to UTC, like so:
Although, per Phrogz comment, if you just want to store timestamps in a location independent way then just use the current UTC time: