views:

31

answers:

2

I have a table Coupon with a field expired_at, which is of datetime type, 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.new
c.expired_at = DateTime.now
c.expired_at_timezone = "Arizona"
c.save!

and in the 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 want the coupon expired at 2014-07-01 10:00 am, Arizona time, the expired_at stored in the db should be 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

A: 

It's better to save all your date in UTC after, you can compare by TimeZone.

shingara
+1  A: 

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
KandadaBoggu
is it possible to rewrite expired_at method in coupon.rb?def expired_at super.in_time_zone(expired_at_timezone)end
leomayleomay
I have updated my answer with the `expired_at` method. To get the current value of `expired_at` you have to access the `attributes` hash.
KandadaBoggu