How to change the timezone of a TimeWithZone object?
I have a model Coupon
with an attribute expired_at
, of class DateTime
and before I save the record, I want to change the zone part of the field according to the user's choice. Say,
c = Coupon.ne开发者_C百科w
c.expired_at = DateTime.now
c.expired_at_timezone = "Arizona"
c.save!
And in coupon.rb
:
class Coupon < ActiveRecord::Base
def before_save
# change the zone part here, leave the date and time part alone
end
end
What I'm saying is if the admin wants the coupon expired at 2014-07-01 10:00 am
, Arizona time, the expired_at
stored in the DB should be something like this:
Tue, 01 Jul 2014 10:00:00 MST -07:00
Is there any way I can modify the zone part only and leave the date and time part alone?
Thanks
You can change the default timezone for your rails application by changing config.time_zone
in your environment.rb
. Usually by default it is set to UTC.
In your case each coupon has its own timezone. So you have to use a different approach.
You don't have to change your save
logic. You just need to change your retrieval
logic. Use the in_time_zone method of Time class.
c = Coupon.last
p c.expired_at.in_time_zone(c.expired_at_timezone)
# => Tue, 09 Mar 2010 02:06:00 MST -07:00
Otherwise you can override the expired_at
method of your Coupon model.
def expired_at
# access the current value of expired_at from attributes hash
attributes["expired_at"].in_time_zone(self.expired_at_timezone)
end
Now you can do the following:
p Coupon.last.expired_at
# => Tue, 09 Mar 2010 02:06:00 MST -07:00
It's better to save all your date in UTC after, you can compare by TimeZone.
精彩评论