2010-03-09 37 views
0

我有一个模型Coupon与属性expired_at,类DateTime和我保存记录之前,我想根据用户的选择更改该字段的区域部分。再说了,如何更改TimeWithZone对象的时区?

c = Coupon.new 
c.expired_at = DateTime.now 
c.expired_at_timezone = "Arizona" 
c.save! 

而且在coupon.rb

class Coupon < ActiveRecord::Base 
    def before_save 
    # change the zone part here, leave the date and time part alone 
    end 
end 

我想说,如果管理员想要的优惠券在过期2014-07-01 10:00 am是,亚利桑那时间,存储在数据库中expired_at应该是这样的:

Tue, 01 Jul 2014 10:00:00 MST -07:00 

有没有什么办法可以修改区域部分而只保留日期和时间部分?

感谢

回答

0

您可以通过更改environment.rb中的config.time_zone来更改您的rails应用程序的默认时区。通常默认情况下它被设置为UTC。

在你的情况下,每张优惠券都有自己的时区。所以你必须使用不同的方法。 您不必更改逻辑save。你只需要改变你的检索 逻辑。使用Time类的in_time_zone方法。

c = Coupon.last 
p c.expired_at.in_time_zone(c.expired_at_timezone) 
# => Tue, 09 Mar 2010 02:06:00 MST -07:00 

否则,您可以覆盖您的优惠券模型的expired_at方法。

def expired_at 
    # access the current value of expired_at from attributes hash 
    attributes["expired_at"].in_time_zone(self.expired_at_timezone) 
end 

现在,你可以做到以下几点:

p Coupon.last.expired_at 
# => Tue, 09 Mar 2010 02:06:00 MST -07:00 
+0

是有可能重写expired_at方法coupon.rb? def expired_at super.in_time_zone(expired_at_timezone) end – leomayleomay 2010-03-09 09:38:10

+0

我用'expired_at'方法更新了我的答案。要获取'expired_at'的当前值,您必须访问'attributes'哈希值。 – 2010-03-09 10:00:53

+1

in_time_zone不会仅更改时区部分。这不是关于作者提问的答案。 – Pencilcheck 2013-07-13 14:43:12

0

这是更好地保存在UTC所有的日期之后,您可以通过时区进行比较。