如何更改TimeWithZone对象的时区?

时间:2010-03-09 08:12:13

标签: ruby-on-rails ruby datetime

我有一个模型Coupon,其属性为expired_at,类为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过期,则存储在数据库中的expired_at应该是这样的:

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

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

由于

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以更改config.time_zone中的environment.rb来更改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