如何更改TimeWithZone对象的时区?

我有一个带有属性expired_at的模型Coupon ,类DateTime ,在我保存记录之前,我想根据用户的选择更改字段的区域部分。 说,

 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亚利桑那州2014-07-01 10:00 am过期,则存储在数据库中的expired_at应该是这样的:

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

有什么办法可以修改区域部分并单独保留日期和时间部分吗?

谢谢

您可以通过更改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 

最好以UTC格式保存所有日期,您可以通过TimeZone进行比较。